SPB Git

Repository Public

OfflineStore.swift 9.9 KB 193 lines swift

1// SP Wallet Core2// File: Sources/SPWalletCore/Persistence/OfflineStore.swift3// Description: The offline, READ-ONLY snapshot store of both apps: the last answers of the server kept as JSON files so that a4//              screen can show « as of … » when there is no network, plus a size-capped cache of media blobs (NFT images).5//              Every snapshot is wrapped with the time it was saved and, when the model has one, the server's own `asOf`;6//              `load` returns the age so that a screen can never present a cached value as current.7//              CONTENT RULE: only what the screens already show — public addresses, balances, history, alerts. NEVER the8//              session token, a passkey assertion, a webhook secret or any other credential: this store is not a keychain,9//              and `save` refuses the keys reserved for them. `removeAll()` is called at sign-out.10//11// Author: Simon-Pierre Boucher12// Contact: contact@spboucher.ai13import Foundation14import CryptoKit1516/** A model that carries the server's own date of validity. */17public protocol ServerDated { var serverAsOf: Date? { get } }1819public enum OfflineStoreError: Error, Sendable, Equatable {20    /** The key is empty, too long, or one of the names reserved for credentials (`session`, `token`, `cookie`, `secret`…). */21    case refusedKey(String)22    /** A single blob larger than the whole media cap is not cached. */23    case blobTooLarge(bytes: Int, cap: Int)24}2526public actor OfflineStore {27    /** One stored snapshot with its dates. */28    public struct Snapshot<T: Codable & Sendable>: Codable, Sendable {29        public let value: T30        /** When this device saved it. */31        public let savedAt: Date32        /** The server's own date of the data (`asOf`), when the model has one. */33        public let asOf: Date?3435        /** The date the data is true for: the server's when known, else when it was saved. */36        public var effectiveDate: Date { asOf ?? savedAt }37        /** Seconds since `effectiveDate`. Never negative (a clock set back does not make data fresh). */38        public func age(now: Date = Date()) -> TimeInterval { max(0, now.timeIntervalSince(effectiveDate)) }39    }4041    private struct BlobEntry: Codable { var file: String; var bytes: Int; var usedAt: Date }4243    public nonisolated let directory: URL44    /** Total bytes of media kept; the least recently used blobs are evicted beyond it. */45    public nonisolated let blobCapBytes: Int46    private let now: @Sendable () -> Date47    private let fm = FileManager()48    private var index: [String: BlobEntry]?4950    private var snapshotsDir: URL { directory.appendingPathComponent("snapshots", isDirectory: true) }51    private var blobsDir: URL { directory.appendingPathComponent("blobs", isDirectory: true) }52    private var indexURL: URL { blobsDir.appendingPathComponent("index.json") }5354    /**55     - Parameters:56       - directory: a directory owned by this store (created on first write). The apps pass a folder of their Application57         Support (or app-group) container; everything below it may be deleted by `removeAll()`.58       - blobCapBytes: cap of the media cache (default 64 MiB).59     */60    public init(directory: URL, blobCapBytes: Int = 64 * 1024 * 1024, now: @escaping @Sendable () -> Date = { Date() }) {61        self.directory = directory; self.blobCapBytes = max(0, blobCapBytes); self.now = now62    }6364    /**65     Atomic write (a temporary file renamed over the target: a crash never leaves half a snapshot).6667     File protection on iOS is `.completeUntilFirstUserAuthentication`, on purpose: the widgets and the background refresh68     run while the device is LOCKED and must read (and refresh) these snapshots; with `.complete` they would fail whenever the69     phone is in a pocket. The files are still encrypted at rest and unreadable after a reboot until the first unlock. This is70     acceptable ONLY because nothing here is a credential: what is stored is what the screens show (public addresses, balances,71     history). Anything secret belongs in the keychain (`SessionTokenStoring`), never here.72     */73    private static var writeOptions: Data.WritingOptions {74        #if os(iOS) || os(tvOS) || os(watchOS) || os(visionOS)75        [.atomic, .completeFileProtectionUntilFirstUserAuthentication]76        #else77        [.atomic]78        #endif79    }8081    private func write(_ data: Data, to url: URL) throws {82        try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)83        try data.write(to: url, options: Self.writeOptions)84        // snapshots can be re-fetched: keep them out of iCloud / iTunes backups85        var u = url, v = URLResourceValues()86        v.isExcludedFromBackup = true87        try? u.setResourceValues(v)88    }8990    // MARK: snapshots9192    private static let reserved = ["session", "token", "cookie", "secret", "passkey", "credential", "password", "privatekey", "seed", "mnemonic"]93    private static func check(_ key: String) throws {94        let k = key.lowercased().filter { $0.isLetter || $0.isNumber }95        guard !key.isEmpty, key.utf8.count <= 200, !reserved.contains(where: k.contains) else { throw OfflineStoreError.refusedKey(key) }96    }97    /** File name of a key: a readable prefix plus a hash, so that any key is a safe, unique file name. */98    private static func fileName(_ key: String, ext: String) -> String {99        let safe = String(key.unicodeScalars.map { CharacterSet.alphanumerics.contains($0) && $0.isASCII ? Character($0) : "_" }.prefix(40))100        let hash = SHA256.hash(data: Data(key.utf8)).prefix(12).map { String(format: "%02x", $0) }.joined()101        return "\(safe)-\(hash).\(ext)"102    }103    private func snapshotURL(_ key: String) -> URL { snapshotsDir.appendingPathComponent(Self.fileName(key, ext: "json")) }104105    /** Save a snapshot under `key` (replacing the previous one). `asOf` defaults to the model's own date when it is `ServerDated`. */106    @discardableResult107    public func save<T: Codable & Sendable>(_ value: T, key: String, asOf: Date? = nil) throws -> Snapshot<T> {108        try Self.check(key)109        let snap = Snapshot(value: value, savedAt: now(), asOf: asOf ?? (value as? ServerDated)?.serverAsOf)110        try write(try APICoding.encoder().encode(snap), to: snapshotURL(key))111        return snap112    }113114    /**115     The snapshot saved under `key`, or nil when there is none. A file that cannot be read back as `T` (truncated, corrupted,116     written by an incompatible version) is DELETED and nil is returned: never a crash, never a half-decoded value.117     */118    public func load<T: Codable & Sendable>(_ key: String, as type: T.Type = T.self) -> Snapshot<T>? {119        let url = snapshotURL(key)120        guard let data = try? Data(contentsOf: url) else { return nil }121        guard let snap = try? APICoding.decoder().decode(Snapshot<T>.self, from: data) else { try? fm.removeItem(at: url); return nil }122        return snap123    }124125    public func remove(_ key: String) { try? fm.removeItem(at: snapshotURL(key)) }126127    // MARK: media blobs (LRU, size-capped)128129    private func loadIndex() -> [String: BlobEntry] {130        if let index { return index }131        var idx = (try? Data(contentsOf: indexURL)).flatMap { try? APICoding.decoder().decode([String: BlobEntry].self, from: $0) } ?? [:]132        // the index is only a cache of the directory: entries without a file are dropped, files without an entry are deleted133        idx = idx.filter { fm.fileExists(atPath: blobsDir.appendingPathComponent($0.value.file).path) }134        let known = Set(idx.values.map(\.file))135        for f in (try? fm.contentsOfDirectory(atPath: blobsDir.path)) ?? [] where f != "index.json" && !known.contains(f) { try? fm.removeItem(at: blobsDir.appendingPathComponent(f)) }136        index = idx137        return idx138    }139    private func storeIndex(_ idx: [String: BlobEntry]) {140        index = idx141        if let d = try? APICoding.encoder().encode(idx) { try? write(d, to: indexURL) }142    }143144    /** Cache a media blob. Evicts the least recently used blobs until the total is within `blobCapBytes`. */145    public func saveBlob(_ data: Data, key: String) throws {146        try Self.check(key)147        guard data.count <= blobCapBytes else { throw OfflineStoreError.blobTooLarge(bytes: data.count, cap: blobCapBytes) }148        var idx = loadIndex()149        let file = Self.fileName(key, ext: "blob")150        try write(data, to: blobsDir.appendingPathComponent(file))151        idx[key] = BlobEntry(file: file, bytes: data.count, usedAt: now())152        var total = idx.values.reduce(0) { $0 + $1.bytes }153        for (k, e) in idx.sorted(by: { $0.value.usedAt < $1.value.usedAt }) where total > blobCapBytes && k != key {154            try? fm.removeItem(at: blobsDir.appendingPathComponent(e.file))155            idx[k] = nil; total -= e.bytes156        }157        storeIndex(idx)158    }159160    /** The cached blob, or nil. Reading it marks it as recently used. A blob whose size no longer matches its index entry is deleted. */161    public func loadBlob(_ key: String) -> Data? {162        var idx = loadIndex()163        guard var e = idx[key] else { return nil }164        let url = blobsDir.appendingPathComponent(e.file)165        guard let data = try? Data(contentsOf: url), data.count == e.bytes else {166            try? fm.removeItem(at: url); idx[key] = nil; storeIndex(idx)167            return nil168        }169        e.usedAt = now(); idx[key] = e170        storeIndex(idx)171        return data172    }173174    public func removeBlob(_ key: String) {175        var idx = loadIndex()176        guard let e = idx[key] else { return }177        try? fm.removeItem(at: blobsDir.appendingPathComponent(e.file))178        idx[key] = nil179        storeIndex(idx)180    }181182    /** Bytes of media currently cached. */183    public func blobBytes() -> Int { loadIndex().values.reduce(0) { $0 + $1.bytes } }184185    // MARK: sign-out186187    /** Erase every snapshot and every blob (sign-out, or the owner's « clear offline data »). The directory itself is removed. */188    public func removeAll() {189        index = [:]190        try? fm.removeItem(at: directory)191    }192}193
Files main
Menu

Theme