SPB Git

Repository Public

NextStoreTests.swift 35.8 KB 483 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/SPMailCore/Tests/SPMailCoreTests/NextStoreTests.swift3// Description: Tests of NextStore (sealed cache, stale-while-revalidate, optimistic mutations, durable queue: replay order, drop on a refusal,4// backoff, survival across a relaunch, wipe) and of SharedContainer (token migration to the shared group, sealed widget snapshot, privacy levels).5import Foundation6import Testing7@testable import SPMailCore89/// A scriptable SP Mail: GET answers by path, a queue of answers for mutations, and a switch that cuts the network.10private final class NextBackend: @unchecked Sendable {11    let server = FakeServer()12    private let lock = NSLock()13    private var gets: [String: String] = [14        "/api/next/labels": #"{"data":[]}"#, "/api/next/searches": #"{"data":[]}"#, "/api/next/snippets": #"{"data":[]}"#, "/api/next/signatures": #"{"data":[]}"#,15        "/api/next/contacts": #"{"data":[],"next_cursor":null}"#, "/api/next/contacts/suggest": #"{"data":[]}"#, "/api/next/push/prefs": #"{"enabled":true,"preview":"sender","quiet_hours":null,"priority_senders":[],"priority_only":false,"mailboxes":{},"badge":"inbox"}"#,16        "/api/next/compose/prefs": #"{"undo_seconds":10,"sensitive":[],"warn_missing_attachment":true,"warn_external":false}"#,17        "/api/next/ai/settings": #"{"provider":"off","consent_external_at":null,"features":{},"language":"auto","available":{"local":true,"anthropic":true}}"#,18        "/api/next/dashboard": #"{"inbox":[],"attention":{"reminders_due":0,"flagged":0,"snoozed_today":0,"unanswered":0},"sync":{"mail_server":"reachable","push":"disabled"}}"#,19    ]20    private var mutations: [StubReply] = []21    private var _offline = false22    private var _unauthorized = false2324    init() {25        server.route { [unowned self] r in26            self.lock.withLock {27                if self._offline { return .offline }28                if self._unauthorized { return .error(401, "unauthenticated") }29                if r.method == "GET" { return self.gets[r.path].map { StubReply.json($0) } ?? .error(404, "not_found") }30                return self.mutations.isEmpty ? .error(500, "unscripted_mutation", message: r.line) : self.mutations.removeFirst()31            }32        }33    }34    var offline: Bool { get { lock.withLock { _offline } } set { lock.withLock { _offline = newValue } } }35    var unauthorized: Bool { get { lock.withLock { _unauthorized } } set { lock.withLock { _unauthorized = newValue } } }36    func set(_ path: String, _ json: String) { lock.withLock { gets[path] = json } }37    func answer(_ replies: StubReply...) { lock.withLock { mutations.append(contentsOf: replies) } }38    /// Requests that change something, in the order they reached the server.39    var writes: [RecordedRequest] { server.requests.filter { $0.method != "GET" } }40    var writeLines: [String] { writes.map(\.line) }41}4243private struct NextRig: Sendable {44    let backend = NextBackend()45    let secrets = InMemorySecretStore()46    let clock = TestClock()47    let dir = FileManager.default.temporaryDirectory.appendingPathComponent("spmail-next-\(UUID().uuidString)")48    /// A new store on the same directory and key: what a relaunch does.49    func store() throws -> NextStore {50        let c = clock51        return try NextStore(directory: dir, secrets: secrets, api: backend.server.api, now: { c.now })52    }53    func cleanup() { try? FileManager.default.removeItem(at: dir) }54}5556private func label(_ id: String, _ name: String, _ color: String = "#1d5fa8", position: Int = 0) -> String {57    "{\"id\":\"\(id)\",\"name\":\"\(name)\",\"color\":\"\(color)\",\"keyword\":\"lbl_\(String(id.filter(\.isHexDigit).prefix(8)).padding(toLength: 8, withPad: "0", startingAt: 0))\",\"position\":\(position)}"58}5960extension NextStore {61    /// Several synchronous reads in one hop (an `await` cannot sit on the right of `&&`).62    func read<T: Sendable>(_ body: @Sendable (isolated NextStore) -> T) -> T { body(self) }63}6465@Suite struct NextStoreTests {66    @Test func refreshFillsTheCacheWhichIsSealedAndSurvivesARelaunchOffline() async throws {67        let rig = NextRig(); defer { rig.cleanup() }68        rig.backend.set("/api/next/labels", "{\"data\":[\(label(uuidA, "Clients-secrets", position: 1)),\(label(uuidB, "Avant", "#b3261e"))]}")69        rig.backend.set("/api/next/snippets", #"{"data":[{"id":"s1","name":"Merci","shortcut":"merci","html":"","text":"Merci beaucoup"}]}"#)70        rig.backend.set("/api/next/contacts", "{\"data\":[\(NextContactsAPITests.contact)],\"next_cursor\":null}")71        rig.backend.set("/api/next/contacts/suggest", #"{"data":[{"name":"Marc","email":"marc@example.com","favorite":false,"score":3}]}"#)72        rig.backend.set("/api/next/compose/prefs", #"{"undo_seconds":30,"sensitive":["@secret.example"],"warn_missing_attachment":true,"warn_external":true}"#)73        let store = try rig.store()74        #expect(await store.read { s in s.labels().isEmpty && s.pushPrefs() == nil && s.isStale(.labels, maxAge: 1e9) && s.refreshedAt(.labels) == nil })7576        let report = try await store.refresh()77        #expect(report.refreshed == Set(NextStore.Collection.allCases) && report.skipped.isEmpty && report.failed.isEmpty && !report.offline && !report.unauthorized)78        #expect(rig.backend.server.lines == ["GET /api/next/labels", "GET /api/next/searches", "GET /api/next/snippets", "GET /api/next/signatures", "GET /api/next/contacts?favorite=1&limit=200",79                                              "GET /api/next/contacts/suggest?q=&limit=50", "GET /api/next/push/prefs", "GET /api/next/compose/prefs", "GET /api/next/ai/settings", "GET /api/next/dashboard"])80        #expect(await store.labels().map(\.name) == ["Avant", "Clients-secrets"])81        #expect(await store.read { s in s.snippets().first?.shortcut == "merci" && s.favoriteContacts().first?.name == "Jeanne Tremblay" && s.composePrefs()?.undoSeconds == 30 && s.pushPrefs()?.preview == .sender })82        #expect(await store.read { s in s.aiSettings()?.provider == .off && s.dashboard()?.sync.mailServer == "reachable" && s.refreshedAt(.labels) == rig.clock.now && !s.isStale(.labels, maxAge: 60) })83        // offline autocomplete over suggestions and favourites84        #expect(await store.read { s in s.suggest("ma").map(\.email) == ["marc@example.com"] && Set(s.suggest("jea").map(\.email)) == ["jeanne@example.com", "jt@perso.example"] })8586        // at rest: sealed — neither names nor addresses appear in the files87        let files = try FileManager.default.contentsOfDirectory(atPath: rig.dir.path).sorted()88        #expect(files == ["next-cache.sealed", "next-queue.sealed"])89        #expect(!fileContains(rig.dir, "Clients-secrets") && !fileContains(rig.dir, "jeanne@example.com") && !fileContains(rig.dir, "labels"))9091        // relaunch with no network: everything is still there; refresh reports offline and keeps the cache92        rig.backend.offline = true93        let again = try rig.store()94        #expect(await again.read { s in s.labels().map(\.name) == ["Avant", "Clients-secrets"] && s.composePrefs()?.sensitive == ["@secret.example"] && s.favoriteContacts().count == 1 })95        let off = try await again.refresh()96        #expect(off.offline && off.refreshed.isEmpty && off.failed.count == 1)97        #expect(await again.labels().count == 2)98        // another key cannot open the files: the cache starts empty instead of failing99        let foreign = try NextStore(directory: rig.dir, secrets: InMemorySecretStore(), api: rig.backend.server.api)100        #expect(await foreign.read { s in s.labels().isEmpty && s.pendingCount == 0 })101    }102103    @Test func optimisticMutationsAreQueuedOfflineAndReplayedInOrderWithTheServerAnswerAsTruth() async throws {104        let rig = NextRig(); defer { rig.cleanup() }105        let old = "44444444-4444-4444-8444-444444444444"106        rig.backend.set("/api/next/labels", "{\"data\":[\(label(uuidA, "Clients")),\(label(old, "Ancien", position: 1))]}")107        let store = try rig.store()108        try await store.refresh([.labels])109        rig.backend.server.reset()110        rig.backend.offline = true111112        // everything below happens with no network and is visible at once113        let made = try #require(await store.createLabel(name: "Urgent", color: "#b3261e"))114        #expect(NextStore.isLocal(made.id) && made.keyword == "" && made.position == 2)115        await store.updateLabel(id: uuidA, name: "Clients VIP")116        await store.createSavedSearch(SavedSearchContent(name: "Non lus", query: "is:unread", pinned: true))117        await store.deleteLabel(id: old)118        await store.setComposePrefs(ComposePrefs(undoSeconds: 20))119        #expect(await store.read { s in s.labels().map(\.name) == ["Clients VIP", "Urgent"] && s.savedSearches().map(\.name) == ["Non lus"] && s.composePrefs()?.undoSeconds == 20 && s.pendingCount == 5 })120        #expect(await store.read { s in s.hasPending(.labels) && s.hasPending(.savedSearches) && !s.hasPending(.snippets) })121122        let blocked = await store.flush()123        #expect(blocked.sent == 0 && blocked.remaining == 5 && blocked.blockedUntil == rig.clock.now.addingTimeInterval(2) && !blocked.unauthorized)124        // while mutations wait, a refresh does not overwrite the collections they touch125        rig.backend.offline = false126        let partial = try await store.refresh([.labels, .savedSearches, .snippets])127        #expect(partial.skipped == [.labels, .savedSearches] && partial.refreshed == [.snippets])128        #expect(await store.labels().map(\.name) == ["Clients VIP", "Urgent"])129130        // back online: one request per mutation, in the order they were made131        rig.backend.server.reset()132        rig.backend.answer(.json(label(uuidC, "Urgent", "#b3261e", position: 2), status: 201), .json(label(uuidA, "Clients VIP")),133                           .json("{\"id\":\"\(uuidB)\",\"name\":\"Non lus\",\"query\":\"is:unread\",\"mailbox_ids\":null,\"pinned\":true,\"position\":0,\"notify\":false}", status: 201),134                           .ok, .json(#"{"undo_seconds":20,"sensitive":[],"warn_missing_attachment":true,"warn_external":false}"#))135        let done = await store.flush(force: true)136        #expect(done.sent == 5 && done.remaining == 0 && done.dropped.isEmpty && done.blockedUntil == nil && done.isIdle)137        #expect(rig.backend.writeLines == ["POST /api/next/labels", "PATCH /api/next/labels/\(uuidA)", "POST /api/next/searches", "DELETE /api/next/labels/\(old)", "PUT /api/next/compose/prefs"])138        #expect(rig.backend.writes[0].json == ["name": "Urgent", "color": "#b3261e"] && rig.backend.writes[1].json == ["name": "Clients VIP"] && rig.backend.writes[2].json == ["name": "Non lus", "query": "is:unread", "pinned": true])139        #expect(rig.backend.writes[4].json == ["undo_seconds": 20, "sensitive": [], "warn_missing_attachment": true, "warn_external": false])140        // the server's rows replaced the optimistic ones: real id, real keyword141        let labels = await store.labels()142        #expect(labels.map(\.id) == [uuidA, uuidC] && labels.last?.keyword == "lbl_33333333" && labels.allSatisfy { !NextStore.isLocal($0.id) })143        #expect(await store.read { s in s.resolvedId(made.id) == uuidC && s.savedSearches().map(\.id) == [uuidB] && s.pendingCount == 0 })144        // an id the interface still holds keeps working after the create was accepted145        rig.backend.answer(.json(label(uuidC, "Très urgent", "#b3261e", position: 2)))146        await store.updateLabel(id: made.id, name: "Très urgent")147        _ = await store.flush()148        let renamed = await store.labels().last?.name149        #expect(rig.backend.writeLines.last == "PATCH /api/next/labels/\(uuidC)" && renamed == "Très urgent")150    }151152    @Test func aRefusalDropsTheMutationAndWhatDependedOnItThenRestoresServerTruth() async throws {153        let rig = NextRig(); defer { rig.cleanup() }154        rig.backend.set("/api/next/labels", "{\"data\":[\(label(uuidA, "Clients"))]}")155        let store = try rig.store()156        try await store.refresh([.labels, .snippets])157        rig.backend.offline = true158        let dup = try #require(await store.createLabel(name: "clients"))159        await store.createSnippet(SnippetContent(name: "Merci", shortcut: "merci", text: "Merci !"))160        await store.updateLabel(id: uuidA, color: "#2e6b2e")161        _ = await store.flush()162        // a rename of the label whose creation has not left yet is folded into that creation163        await store.updateLabel(id: dup.id, name: "clients 2")164        #expect(await store.read { s in s.labels().count == 2 && s.pendingCount == 3 })165166        rig.backend.offline = false167        rig.backend.server.reset()168        rig.backend.answer(.error(409, "name_taken", message: "A label with this name already exists"), .json(##"{"id":"s9","name":"Merci","shortcut":"merci","html":"","text":"Merci !"}"##, status: 201), .json(label(uuidA, "Clients", "#2e6b2e")))169        let report = await store.flush(force: true)170        #expect(report.sent == 2 && report.remaining == 0 && report.blockedUntil == nil)171        #expect(report.dropped == [NextStore.DroppedMutation(collection: .labels, kind: "create", target: dup.id, code: "name_taken", message: "A label with this name already exists")])172        // the refused create went once (with the rename folded into it), the later mutations still went, in order173        #expect(rig.backend.writeLines == ["POST /api/next/labels", "POST /api/next/snippets", "PATCH /api/next/labels/\(uuidA)"])174        #expect(rig.backend.writes[0].json["name"] == "clients 2")175        // the phantom row is gone; the collection was re-read from the server176        #expect(rig.backend.server.lines.last == "GET /api/next/labels")177        #expect(await store.read { s in s.labels().map(\.id) == [uuidA] && s.snippets().map(\.id) == ["s9"] && s.pendingCount == 0 })178179        // other refusals: 400, 404 on an update, 422 — all dropped; 404 on a delete counts as done180        rig.backend.server.reset()181        await store.updateLabel(id: uuidA, name: "")182        await store.deleteSnippet(id: "s9")183        rig.backend.answer(.error(400, "invalid_request", message: "name: too short"), .error(404, "not_found"))184        let second = await store.flush()185        #expect(second.dropped.map(\.code) == ["invalid_request"] && second.sent == 1 && second.remaining == 0 && rig.backend.writeLines == ["PATCH /api/next/labels/\(uuidA)", "DELETE /api/next/snippets/s9"])186        #expect(await store.read { s in s.labels().first?.name == "Clients" && s.snippets().isEmpty })187    }188189    @Test func theQueueSurvivesARelaunchAndTransportOrServerFailuresBackOffWithoutLosingAnything() async throws {190        let rig = NextRig(); defer { rig.cleanup() }191        var store = try rig.store()192        try await store.refresh([.labels])193        rig.backend.offline = true194        await store.createLabel(name: "Un", color: "#b3261e")195        await store.createLabel(name: "Deux", color: "#a14a00")196        let first = await store.flush()197        #expect(first.remaining == 2 && first.blockedUntil == rig.clock.now.addingTimeInterval(2))198        // inside the backoff window nothing is even attempted199        rig.backend.server.reset()200        let waiting = await store.flush()201        #expect(waiting.remaining == 2 && waiting.blockedUntil == first.blockedUntil && rig.backend.server.requests.isEmpty)202        // the window doubles at each failure of the same mutation: 2 s, 4 s, 8 s203        rig.clock.advance(2.5)204        let secondTry = await store.flush()205        #expect(secondTry.blockedUntil == rig.clock.now.addingTimeInterval(4) && rig.backend.writeLines == ["POST /api/next/labels"])206        rig.clock.advance(5)207        #expect(await store.flush().blockedUntil == rig.clock.now.addingTimeInterval(8))208        #expect(!fileContains(rig.dir, "Deux"))209210        // the app is killed and relaunched: the queue and the optimistic rows are still there211        store = try rig.store()212        #expect(await store.read { s in s.pendingCount == 2 && s.labels().map(\.name) == ["Un", "Deux"] && s.queuedForTests.map(\.attempts) == [3, 0] })213        // a 5xx is not a refusal: nothing is dropped, the queue waits214        rig.backend.offline = false215        rig.backend.server.reset()216        rig.backend.answer(.error(502, "mail_server_error"))217        let fivexx = await store.flush()218        #expect(fivexx.sent == 0 && fivexx.dropped.isEmpty && fivexx.remaining == 2 && fivexx.blockedUntil == rig.clock.now.addingTimeInterval(16))219        // a 429 waits what the server asks220        rig.backend.answer(.error(429, "rate_limited", headers: ["Retry-After": "42"]))221        let limited = await store.flush(force: true)222        #expect(limited.remaining == 2 && limited.blockedUntil == rig.clock.now.addingTimeInterval(42) && limited.dropped.isEmpty)223        rig.clock.advance(41)224        #expect(await store.flush().sent == 0)225        rig.clock.advance(2)226        rig.backend.answer(.json(label(uuidA, "Un", "#b3261e"), status: 201), .json(label(uuidB, "Deux", "#a14a00", position: 1), status: 201))227        let done = await store.flush()228        #expect(done.sent == 2 && done.remaining == 0)229        #expect(rig.backend.writes.map { $0.json["name"].stringValue } == ["Un", "Un", "Un", "Deux"])230        #expect(await store.labels().map(\.id) == [uuidA, uuidB])231        // and the relaunch after that sees an empty queue232        let relaunched = try rig.store()233        #expect(await relaunched.pendingCount == 0)234    }235236    @Test func aLostSessionStopsTheQueueAndKeepsIt() async throws {237        let rig = NextRig(); defer { rig.cleanup() }238        let store = try rig.store()239        await store.createLabel(name: "Un")240        rig.backend.unauthorized = true241        let report = await store.flush()242        #expect(report.unauthorized && report.sent == 0 && report.remaining == 1 && report.dropped.isEmpty && report.blockedUntil == nil)243        let refresh = try await store.refresh()244        #expect(refresh.unauthorized && refresh.refreshed.isEmpty)245        #expect(await store.read { s in s.pendingCount == 1 && s.labels().count == 1 })246    }247248    @Test func coalescingKeepsTheLastWriteAndSendsNothingForWhatNeverExisted() async throws {249        let rig = NextRig(); defer { rig.cleanup() }250        rig.backend.set("/api/next/labels", "{\"data\":[\(label(uuidA, "Clients"))]}")251        let store = try rig.store()252        try await store.refresh([.labels, .pushPrefs])253        rig.backend.server.reset()254        // created then renamed twice before anything left: one create with the last name255        let made = try #require(await store.createLabel(name: "A"))256        await store.updateLabel(id: made.id, name: "B")257        await store.updateLabel(id: made.id, name: "C", color: "#7a3fa0")258        // an existing row changed twice: one request, last value of each field259        await store.updateLabel(id: uuidA, name: "X")260        await store.updateLabel(id: uuidA, name: "Y", position: 4)261        // created and deleted: nothing to say262        let ghost = try #require(await store.createSnippet(SnippetContent(name: "Fantôme", text: "x")))263        await store.updateSnippet(id: ghost.id, SnippetContent(text: "y"))264        await store.deleteSnippet(id: ghost.id)265        // preferences written twice: the newer write replaces the older one266        await store.setPushPrefs(PushPrefs(preview: .full))267        await store.setPushPrefs(PushPrefs(preview: PushPreview.none, priorityOnly: true))268        // an update of a row that is then deleted is pointless269        await store.updateLabel(id: uuidA, name: "Z")270        await store.deleteLabel(id: uuidA)271        // updating something unknown or deleted is ignored272        await store.updateLabel(id: "nope", name: "?")273        #expect(await store.queuedForTests.map { "\($0.kind.rawValue) \($0.collection.rawValue)" } == ["create labels", "put pushPrefs", "delete labels"])274        #expect(await store.read { s in s.snippets().isEmpty && s.pushPrefs()?.preview == PushPreview.none && s.labels().map(\.name) == ["C"] })275276        rig.backend.answer(.json(label(uuidC, "C", "#7a3fa0", position: 1), status: 201), .json(##"{"enabled":true,"preview":"none","quiet_hours":null,"priority_senders":[],"priority_only":true,"mailboxes":{},"badge":"inbox"}"##), .ok)277        let report = await store.flush()278        #expect(report.sent == 3 && rig.backend.writeLines == ["POST /api/next/labels", "PUT /api/next/push/prefs", "DELETE /api/next/labels/\(uuidA)"])279        #expect(rig.backend.writes[0].json == ["name": "C", "color": "#7a3fa0"] && rig.backend.writes[1].json["preview"] == "none" && rig.backend.writes[1].json["priority_only"] == true)280        #expect(await store.read { s in s.pushPrefs()?.priorityOnly == true && s.labels().map(\.id) == [uuidC] })281    }282283    @Test func favouritesSignaturesAndAISettings() async throws {284        let rig = NextRig(); defer { rig.cleanup() }285        rig.backend.set("/api/next/signatures", "{\"data\":[{\"id\":\"address:\(uuidC)\",\"source\":\"address\",\"read_only\":true,\"address_id\":\"\(uuidC)\",\"name\":\"a@stg.spboucher.ai\",\"html\":\"\",\"text\":\"Alias\",\"default_for\":[\"\(uuidC)\"],\"default_for_replies\":[]}]}")286        let store = try rig.store()287        try await store.refresh()288        rig.backend.server.reset()289        let contact = try #require(Contact(json: try JSONValue.parse(Data(NextContactsAPITests.contact.utf8))))290        await store.setFavorite(contact, true)291        #expect(await store.favoriteContacts().map(\.id) == [uuidA])292        // read-only per-address signatures are never queued293        await store.updateSignature(id: "address:\(uuidC)", SignatureContent(name: "x"))294        await store.deleteSignature(id: "address:\(uuidC)")295        let sig = try #require(await store.createSignature(SignatureContent(name: "Travail", text: "SP", defaultFor: [uuidC])))296        #expect(!sig.isReadOnly && sig.defaultFor == [uuidC])297        // switching to the external provider without consent: shown at once, refused by the server, undone298        await store.updateAISettings(AISettingsUpdate(provider: .anthropic, features: ["summary": true]))299        #expect(await store.read { s in s.aiSettings()?.provider == .anthropic && s.aiSettings()?.features["summary"] == true && s.pendingCount == 3 })300        rig.backend.answer(.json(NextContactsAPITests.contact), .json("{\"id\":\"\(uuidB)\",\"source\":\"user\",\"read_only\":false,\"name\":\"Travail\",\"html\":\"\",\"text\":\"SP\",\"default_for\":[\"\(uuidC)\"],\"default_for_replies\":[]}", status: 201),301                           .error(412, "consent_required"))302        let report = await store.flush()303        #expect(rig.backend.writeLines == ["PATCH /api/next/contacts/\(uuidA)", "POST /api/next/signatures", "PUT /api/next/ai/settings"])304        #expect(rig.backend.writes[0].json == ["favorite": true] && rig.backend.writes[2].json == ["provider": "anthropic", "features": ["summary": true]])305        #expect(report.sent == 2 && report.dropped.map(\.collection) == [.aiSettings] && report.dropped.first?.code == "consent_required")306        #expect(await store.read { s in s.aiSettings()?.provider == .off && s.signatures().map(\.id) == ["address:\(uuidC)", uuidB] && s.favoriteContacts().first?.stats.received == 9 })307        // with consent it goes through and the consent flag is not kept in the cache308        rig.backend.answer(.json(#"{"provider":"anthropic","consent_external_at":"2026-12-01T13:00:00Z","features":{"summary":true},"language":"auto","available":{"local":true,"anthropic":true}}"#))309        await store.updateAISettings(AISettingsUpdate(provider: .anthropic, consentExternal: true))310        #expect(await store.aiSettings()?.hasExternalConsent == false)311        _ = await store.flush()312        let consented = await store.aiSettings()?.hasExternalConsent313        #expect(rig.backend.writes.last?.json == ["provider": "anthropic", "consent_external": true] && consented == true)314        // unfavourite: the row leaves the cached favourites at once and stays out after the answer315        rig.backend.answer(.json(NextContactsAPITests.contact.replacingOccurrences(of: #""favorite":true"#, with: #""favorite":false"#)))316        await store.setFavorite(contact, false)317        #expect(await store.favoriteContacts().isEmpty)318        _ = await store.flush()319        let favourites = await store.favoriteContacts()320        #expect(rig.backend.writes.last?.json == ["favorite": false] && favourites.isEmpty)321    }322323    @Test func staleWhileRevalidateServesTheCacheAndAnnouncesTheUpdate() async throws {324        let rig = NextRig(); defer { rig.cleanup() }325        rig.backend.set("/api/next/labels", "{\"data\":[\(label(uuidA, "Clients"))]}")326        let store = try rig.store()327        let changes = await store.changes()328        // never fetched: the read returns at once (empty) and a refresh starts in the background329        await store.revalidate([.labels], maxAge: 300)330        var iterator = changes.makeAsyncIterator()331        let first = await iterator.next()332        #expect(first == [.labels] && rig.backend.server.lines == ["GET /api/next/labels"])333        #expect(await store.labels().map(\.name) == ["Clients"])334        // fresh: nothing is fetched335        await store.revalidate([.labels], maxAge: 300)336        try await Task.sleep(for: .milliseconds(50))337        #expect(rig.backend.server.requests.count == 1)338        // stale: the cached value is still served, then replaced339        rig.clock.advance(301)340        rig.backend.set("/api/next/labels", "{\"data\":[\(label(uuidA, "Clients")),\(label(uuidB, "Nouveau", position: 1))]}")341        await store.revalidate([.labels], maxAge: 300)342        #expect(await store.labels().count >= 1)343        let second = await iterator.next()344        #expect(second == [.labels] && rig.backend.server.requests.count == 2)345        #expect(await store.labels().map(\.name) == ["Clients", "Nouveau"])346        // an optimistic mutation is announced too347        rig.backend.offline = true348        await store.deleteLabel(id: uuidB)349        #expect(await iterator.next() == [.labels])350    }351352    @Test func wipeRemovesTheCacheAndTheQueueFromMemoryAndDisk() async throws {353        let rig = NextRig(); defer { rig.cleanup() }354        rig.backend.set("/api/next/labels", "{\"data\":[\(label(uuidA, "Clients"))]}")355        let store = try rig.store()356        try await store.refresh()357        rig.backend.offline = true358        await store.createLabel(name: "En attente")359        _ = await store.flush()360        #expect(await store.read { s in s.pendingCount == 1 && s.labels().count == 2 && s.blockedUntilForTests != nil })361        #expect(try FileManager.default.contentsOfDirectory(atPath: rig.dir.path).count == 2)362363        await store.wipe()364        #expect(await store.read { s in s.pendingCount == 0 && s.labels().isEmpty && s.pushPrefs() == nil && s.dashboard() == nil && s.blockedUntilForTests == nil && s.refreshedAt(.labels) == nil })365        #expect(try FileManager.default.contentsOfDirectory(atPath: rig.dir.path).isEmpty)366        // nothing comes back at the next launch, and nothing is sent for the wiped queue367        rig.backend.offline = false368        rig.backend.server.reset()369        let again = try rig.store()370        #expect(await again.read { s in s.pendingCount == 0 && s.labels().isEmpty })371        let nothing = await again.flush()372        #expect(nothing.sent == 0 && rig.backend.writes.isEmpty)373        // the cache key belongs to the mail cache: it is left in place374        #expect(rig.secrets.read(SecretKeys.cacheKey)?.count == 32)375    }376}377378@Suite struct SharedContainerTests {379    @Test func identifiersAndAccessGroups() {380        let prod = SharedContainer(teamPrefix: "ABCDE12345")381        #expect(prod.groupIdentifier == "group.ai.spboucher.spmail" && prod.keychainAccessGroup == "ABCDE12345.group.ai.spboucher.spmail")382        let dev = SharedContainer(dev: true, teamPrefix: "ABCDE12345")383        #expect(dev.groupIdentifier == "group.ai.spboucher.spmail.dev" && dev.keychainAccessGroup == "ABCDE12345.group.ai.spboucher.spmail.dev")384        #expect(SharedContainer().keychainAccessGroup == nil && SharedContainer(teamPrefix: "").keychainAccessGroup == nil)385        let store = prod.secrets(dataProtection: false)386        #expect(store.service == "ai.spboucher.spmail.shared" && store.accessGroup == "ABCDE12345.group.ai.spboucher.spmail" && !store.dataProtection)387        let tmp = FileManager.default.temporaryDirectory.appendingPathComponent("spmail-group-\(UUID().uuidString)")388        #expect(SharedContainer(directory: tmp).directory == tmp && SharedContainer(directory: tmp).isAvailable)389    }390391    @Test func tokenMigrationCopiesAndKeepsTheOriginal() throws {392        let original = InMemorySecretStore(), shared = InMemorySecretStore()393        #expect(try SharedContainer.migrateToken(from: original, to: shared) == .signedOut && SharedContainer.token(in: shared) == nil)394        original.write(SecretKeys.bearerToken, Data("tok-1".utf8))395        original.write(SecretKeys.cacheKey, Data(repeating: 7, count: 32))396        #expect(try SharedContainer.migrateToken(from: original, to: shared) == .copied)397        #expect(try SharedContainer.token(in: shared) == "tok-1" && original.read(SecretKeys.bearerToken) == Data("tok-1".utf8))398        // the key of the mail cache is never shared399        #expect(shared.read(SecretKeys.cacheKey) == nil)400        #expect(try SharedContainer.migrateToken(from: original, to: shared) == .upToDate)401        // a new sign-in replaces the shared copy; a sign-out removes it402        original.write(SecretKeys.bearerToken, Data("tok-2".utf8))403        #expect(try SharedContainer.migrateToken(from: original, to: shared) == .copied && SharedContainer.token(in: shared) == "tok-2")404        original.delete(SecretKeys.bearerToken)405        #expect(try SharedContainer.migrateToken(from: original, to: shared) == .signedOut && SharedContainer.token(in: shared) == nil)406        shared.write(SecretKeys.bearerToken, Data())407        #expect(try SharedContainer.token(in: shared) == nil)408    }409410    private func results() throws -> [SearchResult] {411        func hit(_ id: String, _ at: String, _ keywords: String) -> JSONValue {412            ["mailbox_id": .string(uuidA), "email_id": .string(id), "thread_id": .string("T" + id), "from": [["name": "Jeanne Tremblay", "email": "jeanne@example.com"]], "subject": .string("Sujet confidentiel \(id)"),413             "preview": .string(String(repeating: "aperçu ", count: 40)), "received_at": .string(at), "keywords": JSONValue(keywords.isEmpty ? [] : [keywords])]414        }415        return (1...12).compactMap { SearchResult(json: hit("M\($0)", String(format: "2026-12-01T%02d:00:00Z", $0), $0 % 2 == 0 ? "$seen" : "")) }416    }417    private func reminders(now: Date) -> [Reminder] {418        func r(_ id: String, _ status: String, _ offset: TimeInterval) -> JSONValue {419            ["id": .string(id), "mailbox_id": .string(uuidA), "email_id": .string("M" + id), "subject": "Relance secrète", "counterpart": ["name": "Marc", "email": "marc@example.com"], "due_at": .string(ISODate.string(now.addingTimeInterval(offset))), "status": .string(status)]420        }421        return [r("1", "due", -3600), r("2", "pending", -60), r("3", "pending", 3600), r("4", "done", -7200), r("5", "due", -10)].compactMap(Reminder.init(json:))422    }423424    @Test func snapshotContentFollowsThePreviewPrivacyLevel() throws {425        let now = Date(timeIntervalSince1970: 1_796_140_000)426        let unread = [WidgetSnapshot.MailboxCount(mailboxId: uuidA, address: "a@stg.spboucher.ai", unread: 3), WidgetSnapshot.MailboxCount(mailboxId: uuidB, address: "b@stg.spboucher.ai", unread: 4)]427        let full = WidgetSnapshot(unread: unread, recent: try results(), reminders: reminders(now: now), preview: .full, limit: 3, generatedAt: now)428        #expect(full.totalUnread == 7 && full.previewLevel == "full" && full.version == 1 && full.conversations.map(\.emailId) == ["M12", "M11", "M10"])429        #expect(full.conversations[0].sender == "Jeanne Tremblay" && full.conversations[0].subject == "Sujet confidentiel M12" && full.conversations[0].preview?.count == 140 && full.conversations[0].preview?.hasSuffix("…") == true)430        #expect(!full.conversations[0].unread && full.conversations[1].unread)431        #expect(full.remindersDue == 3 && full.reminders.map(\.id) == ["1", "2", "5"] && full.reminders[0].subject == "Relance secrète" && full.reminders[0].counterpart == "Marc")432433        let sender = WidgetSnapshot(unread: unread, recent: try results(), reminders: reminders(now: now), preview: .sender, generatedAt: now)434        #expect(sender.conversations.count == 5 && sender.conversations.allSatisfy { $0.sender == "Jeanne Tremblay" && $0.subject == nil && $0.preview == nil })435        #expect(sender.reminders.allSatisfy { $0.subject == nil && $0.counterpart == "Marc" })436437        for level in [PushPreview.none, .unknown] {438            let hidden = WidgetSnapshot(unread: unread, recent: try results(), reminders: reminders(now: now), preview: level, limit: 100, generatedAt: now)439            #expect(hidden.previewLevel == "none" && hidden.conversations.count == 8 && hidden.conversations.allSatisfy { $0.sender == nil && $0.subject == nil && $0.preview == nil })440            #expect(hidden.reminders.allSatisfy { $0.subject == nil && $0.counterpart == nil } && hidden.totalUnread == 7 && hidden.remindersDue == 3)441            // nothing private is in the encoded snapshot at all442            let encoded = String(decoding: try JSONEncoder().encode(hidden), as: UTF8.self)443            #expect(!encoded.contains("Jeanne") && !encoded.contains("confidentiel") && !encoded.contains("aperçu") && !encoded.contains("Marc") && !encoded.contains("secrète"))444        }445        #expect(!full.isStale(now: now.addingTimeInterval(600)) && full.isStale(now: now.addingTimeInterval(3601)))446        let dash = Dashboard(json: ["inbox": [["mailbox_id": .string(uuidA), "address": "a@stg.spboucher.ai", "unread": 9, "total": 20]], "attention": ["reminders_due": 6]])447        let fromDash = WidgetSnapshot(dashboard: dash, recent: [], preview: .full, generatedAt: now)448        #expect(fromDash.totalUnread == 9 && fromDash.remindersDue == 6 && fromDash.conversations.isEmpty)449    }450451    @Test func snapshotIsSealedReadableByTheExtensionAndGoneAfterSignOut() throws {452        let dir = FileManager.default.temporaryDirectory.appendingPathComponent("spmail-group-\(UUID().uuidString)")453        defer { try? FileManager.default.removeItem(at: dir) }454        let container = SharedContainer(dev: true, directory: dir)455        let shared = InMemorySecretStore()456        #expect(container.readSnapshot(shared: shared) == nil)457        let now = Date(timeIntervalSince1970: 1_796_140_000)458        let snap = WidgetSnapshot(unread: [WidgetSnapshot.MailboxCount(mailboxId: uuidA, address: "a@stg.spboucher.ai", unread: 3)], recent: try results(), reminders: reminders(now: now), preview: .full, generatedAt: now)459        try container.write(snap, shared: shared)460        // the extension: another instance, same group directory, same shared keychain461        #expect(SharedContainer(dev: true, directory: dir).readSnapshot(shared: shared) == snap)462        #expect(!fileContains(dir, "Jeanne") && !fileContains(dir, "confidentiel") && !fileContains(dir, "a@stg.spboucher.ai") && !fileContains(dir, "unread"))463        // its own key, not the mail cache key464        #expect(shared.read(SharedContainer.snapshotKeyName)?.count == 32 && shared.read(SecretKeys.cacheKey) == nil)465        // without the key, or with another one, there is simply no snapshot466        #expect(container.readSnapshot(shared: InMemorySecretStore()) == nil)467        let other = InMemorySecretStore()468        other.write(SharedContainer.snapshotKeyName, Data(repeating: 1, count: 32))469        #expect(container.readSnapshot(shared: other) == nil)470        // a tampered file is not opened471        let file = dir.appendingPathComponent(SharedContainer.snapshotFile)472        var bytes = try Data(contentsOf: file)473        bytes[bytes.count - 1] ^= 0xff474        try bytes.write(to: file)475        #expect(container.readSnapshot(shared: shared) == nil)476        // sign-out477        try container.write(snap, shared: shared)478        shared.write(SecretKeys.bearerToken, Data("tok".utf8))479        try container.clear(shared: shared)480        #expect(container.readSnapshot(shared: shared) == nil && shared.read(SecretKeys.bearerToken) == nil && shared.read(SharedContainer.snapshotKeyName) == nil && !FileManager.default.fileExists(atPath: file.path))481    }482}483
Files main
Menu

Theme