SPB Git

Repository Public

DiskCache.swift 7.1 KB 152 lines swift

1//2//  VQuant iOS3//  File: Core/Cache/DiskCache.swift4//  Description: Encrypted on-device cache (AES-GCM, key held in the Keychain) and the data-freshness vocabulary of the app.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//910import CryptoKit11import Foundation1213/// Where a displayed value came from and how old it is. Shown next to every market figure.14enum DataFreshness: Equatable, Sendable {15    /// Fetched just now and the provider's last trade is recent while the market is open.16    case live17    /// Fetched just now, but the provider's last trade is older than the live threshold during market hours.18    case delayed(asOf: Date)19    /// Fetched just now, market closed (or end-of-day series): the last official values.20    case historical(asOf: Date?)21    /// Read from the device because the network failed. `savedAt` is when it was fetched.22    case cached(savedAt: Date)23    case unavailable2425    static let liveThreshold: TimeInterval = 1202627    static func classify(origin: DataOrigin, quoteTime: Date?, marketOpen: Bool?, now: Date = Date()) -> DataFreshness {28        switch origin {29        case .cache(let savedAt): return .cached(savedAt: savedAt)30        case .network:31            guard let quoteTime else { return .historical(asOf: nil) }32            let age = now.timeIntervalSince(quoteTime)33            if marketOpen == false { return .historical(asOf: quoteTime) }34            if age <= liveThreshold { return .live }35            // Market state unknown and an old trade: do not call it delayed-live, it is the last known value.36            if marketOpen == nil && age > 3600 { return .historical(asOf: quoteTime) }37            return .delayed(asOf: quoteTime)38        }39    }4041    var isStale: Bool { if case .cached = self { return true } else { return false } }42}4344/// A value together with its provenance.45struct Loaded<Value> {46    var value: Value47    var origin: DataOrigin48    var fetchedAt: Date49    var isFromCache: Bool { if case .cache = origin { return true } else { return false } }50}51extension Loaded: Sendable where Value: Sendable {}52enum DataOrigin: Equatable, Sendable { case network, cache(savedAt: Date) }5354protocol CacheKeyProvider: Sendable {55    /// 32 random bytes, created on first use and kept on this device only.56    func key() -> SymmetricKey57}5859struct FixedCacheKey: CacheKeyProvider {60    let raw: Data61    init(_ raw: Data = Data((0..<32).map { _ in UInt8.random(in: 0...255) })) { self.raw = raw }62    func key() -> SymmetricKey { SymmetricKey(data: raw) }63}6465/// File cache. Each entry is one file: AES-256-GCM of the payload, named by the SHA-256 of its key, with the66/// save time authenticated as associated data. Files are also covered by iOS Data Protection.67actor DiskCache {68    private let directory: URL69    private let keyProvider: CacheKeyProvider70    private let fm = FileManager.default7172    init(directory: URL, keyProvider: CacheKeyProvider) {73        self.directory = directory74        self.keyProvider = keyProvider75        try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)76        var values = URLResourceValues(); values.isExcludedFromBackup = true77        var d = directory; try? d.setResourceValues(values)78    }7980    private func url(_ key: String) -> URL {81        let digest = SHA256.hash(data: Data(key.utf8)).map { String(format: "%02x", $0) }.joined()82        return directory.appendingPathComponent(digest + ".vqc")83    }8485    func save(_ key: String, _ data: Data, at date: Date = Date()) {86        var stamp = date.timeIntervalSince1970.bitPattern.bigEndian87        let header = Data(bytes: &stamp, count: 8)88        guard let box = try? AES.GCM.seal(data, using: keyProvider.key(), authenticating: header), let combined = box.combined else { return }89        let target = url(key)90        try? (header + combined).write(to: target, options: [.atomic, .completeFileProtectionUnlessOpen])91    }9293    func load(_ key: String) -> (data: Data, savedAt: Date)? {94        guard let raw = try? Data(contentsOf: url(key)), raw.count > 8 + 28 else { return nil }95        let header = raw.prefix(8)96        let bits = header.reduce(UInt64(0)) { ($0 << 8) | UInt64($1) }97        guard let box = try? AES.GCM.SealedBox(combined: raw.dropFirst(8)), let data = try? AES.GCM.open(box, using: keyProvider.key(), authenticating: header) else {98            try? fm.removeItem(at: url(key))                     // tampered, truncated, or written under a previous key99            return nil100        }101        return (data, Date(timeIntervalSince1970: Double(bitPattern: bits)))102    }103104    func remove(_ key: String) { try? fm.removeItem(at: url(key)) }105106    func removeAll() {107        for f in (try? fm.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)) ?? [] { try? fm.removeItem(at: f) }108    }109110    /// Bytes on disk.111    func size() -> Int {112        let files = (try? fm.contentsOfDirectory(at: directory, includingPropertiesForKeys: [.fileSizeKey])) ?? []113        return files.reduce(0) { $0 + ((try? $1.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0) }114    }115116    /// Drops entries older than `maxAge` and, beyond `maxBytes`, the least recently written ones.117    func trim(maxAge: TimeInterval = 30 * 86_400, maxBytes: Int = 400 * 1_048_576, now: Date = Date()) {118        let keys: [URLResourceKey] = [.contentModificationDateKey, .fileSizeKey]119        var entries = ((try? fm.contentsOfDirectory(at: directory, includingPropertiesForKeys: keys)) ?? []).compactMap { u -> (URL, Date, Int)? in120            guard let v = try? u.resourceValues(forKeys: Set(keys)), let d = v.contentModificationDate else { return nil }121            return (u, d, v.fileSize ?? 0)122        }123        for e in entries where now.timeIntervalSince(e.1) > maxAge { try? fm.removeItem(at: e.0) }124        entries.removeAll { now.timeIntervalSince($0.1) > maxAge }125        var total = entries.reduce(0) { $0 + $1.2 }126        for e in entries.sorted(by: { $0.1 < $1.1 }) where total > maxBytes { try? fm.removeItem(at: e.0); total -= e.2 }127    }128}129130/// Network first, device copy when the network fails. Every read says which of the two it returned.131struct CachedFetcher: Sendable {132    let cache: DiskCache133134    func load<T: Codable & Sendable>(_ key: String, _ type: T.Type = T.self, fetch: @Sendable () async throws -> T) async throws -> Loaded<T> {135        do {136            let value = try await fetch()137            if let data = try? JSONEncoder().encode(value) { await cache.save(key, data) }138            return Loaded(value: value, origin: .network, fetchedAt: Date())139        } catch {140            let e = APIError.from(error)141            // Only a transport failure falls back to the device copy: a refusal (401, 404…) is a real answer.142            guard e.kind == .offline || e.kind == .network || e.kind == .server, let hit = await cached(key, T.self) else { throw e }143            return hit144        }145    }146147    func cached<T: Codable & Sendable>(_ key: String, _ type: T.Type = T.self) async -> Loaded<T>? {148        guard let (data, savedAt) = await cache.load(key), let value = try? JSONDecoder().decode(T.self, from: data) else { return nil }149        return Loaded(value: value, origin: .cache(savedAt: savedAt), fetchedAt: savedAt)150    }151}152
Files main
Menu

Theme