SPB Git

Repository Public

OfflineStoreTests.swift 9.7 KB 173 lines swift

1// SP Wallet Core2// File: Tests/SPWalletCoreTests/OfflineStoreTests.swift3// Description: The offline snapshot store: round trip with dates and age, corruption (nil + deletion, never a crash), the LRU4//              media cache and its cap, sign-out, concurrent writes, and the refusal of credential-like keys.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import Testing10@testable import SPWalletCore1112private final class TestClock: @unchecked Sendable {13    private let lock = NSLock()14    private var t: Date15    init(_ t: Date) { self.t = t }16    var now: Date { lock.withLock { t } }17    func advance(_ s: TimeInterval) { lock.withLock { t = t.addingTimeInterval(s) } }18}1920private struct Dated: Codable, Sendable, Equatable, ServerDated {21    let asOf: Date22    let balances: [String: String]23    var serverAsOf: Date? { asOf }24}2526@Suite struct OfflineStoreTests {27    let dir = FileManager.default.temporaryDirectory.appendingPathComponent("spw-offline-\(UUID().uuidString)", isDirectory: true)28    let t0 = Date(timeIntervalSince1970: 1_795_000_000)2930    private func files(_ sub: String) -> [String] { ((try? FileManager.default.contentsOfDirectory(atPath: dir.appendingPathComponent(sub).path)) ?? []).sorted() }3132    @Test func roundTripWithSavedAtServerAsOfAndAge() async throws {33        let clock = TestClock(t0)34        let store = OfflineStore(directory: dir, now: { clock.now })35        defer { try? FileManager.default.removeItem(at: dir) }3637        // a real model of the API, exactly as decoded38        let page: AlertPage = try TestResources.json("ops-alerts.json")["list"]!.decode()39        try await store.save(page, key: "alerts/list")40        clock.advance(90)41        let back = try #require(await store.load("alerts/list", as: AlertPage.self))42        #expect(back.value == page && back.savedAt == t0 && back.asOf == nil && back.effectiveDate == t0)43        #expect(back.age(now: clock.now) == 90)4445        // the server's own date wins over the time of saving; a clock set back never yields a negative age46        let serverDate = t0.addingTimeInterval(-600)47        let snap = try await store.save(Dated(asOf: serverDate, balances: ["base:native": "1000000000000000"]), key: "portfolio")48        #expect(snap.asOf == serverDate && snap.savedAt == clock.now)49        let p = try #require(await store.load("portfolio", as: Dated.self))50        #expect(p.value.balances == ["base:native": "1000000000000000"] && p.asOf == serverDate && p.age(now: clock.now) == 690)51        #expect(p.age(now: serverDate.addingTimeInterval(-5)) == 0)52        let explicit = try await store.save(["a": 1], key: "explicit", asOf: t0)53        #expect(explicit.asOf == t0)5455        #expect(await store.load("missing", as: AlertPage.self) == nil)56        // keys with separators and unicode map to distinct, safe file names57        try await store.save(1, key: "nft/base/0xabc/1"); try await store.save(2, key: "nft/base/0xabc_1")58        #expect(await store.load("nft/base/0xabc/1", as: Int.self)?.value == 1)59        #expect(await store.load("nft/base/0xabc_1", as: Int.self)?.value == 2)60        #expect(files("snapshots").allSatisfy { !$0.contains("/") && $0.hasSuffix(".json") })61        await store.remove("explicit")62        #expect(await store.load("explicit", as: [String: Int].self) == nil)63    }6465    @Test func aCorruptedOrIncompatibleFileIsNilAndDeleted() async throws {66        let store = OfflineStore(directory: dir)67        defer { try? FileManager.default.removeItem(at: dir) }68        try await store.save(Dated(asOf: t0, balances: [:]), key: "portfolio")69        let file = dir.appendingPathComponent("snapshots").appendingPathComponent(try #require(files("snapshots").first))7071        // truncated72        try Data(try Data(contentsOf: file).prefix(20)).write(to: file)73        #expect(await store.load("portfolio", as: Dated.self) == nil)74        #expect(!FileManager.default.fileExists(atPath: file.path))7576        // garbage bytes77        try await store.save(Dated(asOf: t0, balances: [:]), key: "portfolio")78        try Data([0xff, 0x00, 0xfe, 0x7b]).write(to: file)79        #expect(await store.load("portfolio", as: Dated.self) == nil && files("snapshots").isEmpty)8081        // valid JSON of another shape (an older app version): not half-decoded82        try await store.save(["x": "y"], key: "portfolio")83        #expect(await store.load("portfolio", as: Dated.self) == nil && files("snapshots").isEmpty)84    }8586    @Test func blobsAreCappedWithLeastRecentlyUsedEviction() async throws {87        let clock = TestClock(t0)88        let store = OfflineStore(directory: dir, blobCapBytes: 250, now: { clock.now })89        defer { try? FileManager.default.removeItem(at: dir) }90        func blob(_ b: UInt8) -> Data { Data(repeating: b, count: 100) }9192        try await store.saveBlob(blob(1), key: "nft/a"); clock.advance(1)93        try await store.saveBlob(blob(2), key: "nft/b"); clock.advance(1)94        #expect(await store.blobBytes() == 200)95        #expect(await store.loadBlob("nft/a") == blob(1)); clock.advance(1)   // « a » is now the most recently used96        try await store.saveBlob(blob(3), key: "nft/c")                        // 300 > 250: the least recently used (« b ») goes97        #expect(await store.loadBlob("nft/b") == nil)98        #expect(await store.loadBlob("nft/a") == blob(1))99        #expect(await store.loadBlob("nft/c") == blob(3))100        #expect(await store.blobBytes() == 200 && files("blobs").filter { $0.hasSuffix(".blob") }.count == 2)101102        // replacing a key does not double-count it; a blob larger than the whole cap is refused103        clock.advance(1)104        try await store.saveBlob(Data(repeating: 9, count: 120), key: "nft/a")105        #expect(await store.blobBytes() == 220)106        await #expect(throws: OfflineStoreError.blobTooLarge(bytes: 251, cap: 250)) { try await store.saveBlob(Data(count: 251), key: "nft/huge") }107108        // the cap survives a restart (the index is on disk), and a blob damaged on disk is dropped, not served109        let again = OfflineStore(directory: dir, blobCapBytes: 250, now: { clock.now })110        #expect(await again.blobBytes() == 220)111        let cFile = dir.appendingPathComponent("blobs").appendingPathComponent(try #require(files("blobs").first { $0.hasPrefix("nft_c") }))112        try Data([1, 2, 3]).write(to: cFile)113        #expect(await again.loadBlob("nft/c") == nil)114        #expect(await again.blobBytes() == 120)115        await again.removeBlob("nft/a")116        #expect(await again.blobBytes() == 0)117        #expect(await again.loadBlob("nft/a") == nil)118119        // a corrupted index is not a crash: the cache starts empty and orphan files are cleaned120        try await again.saveBlob(blob(7), key: "nft/z")121        try Data("not json".utf8).write(to: dir.appendingPathComponent("blobs/index.json"))122        let third = OfflineStore(directory: dir, blobCapBytes: 250)123        #expect(await third.loadBlob("nft/z") == nil)124        #expect(await third.blobBytes() == 0)125        #expect(files("blobs").filter { $0.hasSuffix(".blob") }.isEmpty)126    }127128    @Test func removeAllErasesEverythingAndTheStoreStaysUsable() async throws {129        let store = OfflineStore(directory: dir)130        defer { try? FileManager.default.removeItem(at: dir) }131        try await store.save(["a": "b"], key: "accounts")132        try await store.saveBlob(Data([1, 2, 3]), key: "nft/a")133        await store.removeAll()134        #expect(!FileManager.default.fileExists(atPath: dir.path))135        #expect(await store.load("accounts", as: [String: String].self) == nil)136        #expect(await store.loadBlob("nft/a") == nil)137        #expect(await store.blobBytes() == 0)138        try await store.save(["a": "c"], key: "accounts")139        #expect(await store.load("accounts", as: [String: String].self)?.value == ["a": "c"])140    }141142    @Test func concurrentWritesNeverLeaveAHalfWrittenFile() async throws {143        let store = OfflineStore(directory: dir, blobCapBytes: 1000)144        defer { try? FileManager.default.removeItem(at: dir) }145        await withTaskGroup(of: Void.self) { g in146            for i in 0..<60 {147                g.addTask { _ = try? await store.save(Dated(asOf: Date(timeIntervalSince1970: Double(i)), balances: ["k": String(repeating: "9", count: 2000 + i)]), key: "same") }148                g.addTask { _ = try? await store.save(i, key: "key-\(i)") }149                g.addTask { _ = try? await store.saveBlob(Data(repeating: UInt8(i), count: 100), key: "blob-\(i % 20)") }150                g.addTask { _ = await store.load("same", as: Dated.self); _ = await store.loadBlob("blob-\(i % 20)") }151            }152        }153        let same = try #require(await store.load("same", as: Dated.self))154        let i = Int(same.value.asOf.timeIntervalSince1970)155        #expect(same.value.balances["k"]?.count == 2000 + i)                // one writer's whole value, never a mix156        for i in 0..<60 { #expect(await store.load("key-\(i)", as: Int.self)?.value == i) }157        #expect(await store.blobBytes() <= 1000)158        #expect(files("snapshots").count == 61 && files("snapshots").allSatisfy { $0.hasSuffix(".json") }) // no temporary file left behind159    }160161    @Test func credentialsAreRefusedByName() async throws {162        let store = OfflineStore(directory: dir)163        defer { try? FileManager.default.removeItem(at: dir) }164        for key in ["session", "sessionToken", "auth/cookie", "webhook-secret", "Session_Token", "passkey", ""] {165            await #expect(throws: OfflineStoreError.refusedKey(key)) { try await store.save("x", key: key) }166            await #expect(throws: OfflineStoreError.refusedKey(key)) { try await store.saveBlob(Data([1]), key: key) }167        }168        #expect(files("snapshots").isEmpty)169        // the one-time webhook secret cannot even be handed to the store: it is not Encodable170        #expect(!(AlertWebhookSecret.self is Encodable.Type))171    }172}173
Files main
Menu

Theme