Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Cache/DiskCache.swift3// Description: The offline store: what was last received from the server, with the time it was received, encrypted at rest.4import CryptoKit5import Foundation6import os78/// How old a displayed value is, in words the interface can show next to it. The app has no streaming feed: every9/// market value is a provider quote fetched over HTTPS, so nothing is ever labelled "live".10public enum Freshness: Sendable, Equatable {11 /// the provider's own timestamp is recent (within `recentWindow`)12 case recent(asOf: Date)13 /// received now, but the provider's timestamp is older (closed market, delayed feed)14 case delayed(asOf: Date)15 /// end-of-day or older series: a historical record, not a current price16 case historical(through: Date?)17 /// read from this Mac's cache because the server could not be reached18 case cached(fetched: Date)19 case unavailable(String)2021 public static let recentWindow: TimeInterval = 1202223 /// Classifies a quote received from the server at `now`.24 public static func ofQuote(asOf: Date?, now: Date = Date()) -> Freshness {25 guard let asOf else { return .unavailable("The provider sent no timestamp for this quote.") }26 return now.timeIntervalSince(asOf) <= recentWindow ? .recent(asOf: asOf) : .delayed(asOf: asOf)27 }2829 public var label: String {30 switch self { case .recent: "Recent"; case .delayed: "Delayed"; case .historical: "Historical"; case .cached: "Cached"; case .unavailable: "Unavailable" }31 }32 public var isCurrent: Bool { if case .recent = self { true } else { false } }33}3435public struct Cached<T: Sendable>: Sendable {36 public var value: T37 public var fetchedAt: Date38 /// true when the value comes from disk because the network call failed39 public var fromCache: Bool40 public init(value: T, fetchedAt: Date, fromCache: Bool) { self.value = value; self.fetchedAt = fetchedAt; self.fromCache = fromCache }41}4243/// Files under Application Support, one per key, sealed with AES-GCM under a key kept in the Keychain (or supplied by44/// tests). Cached research and portfolio data are therefore unreadable from a copy of the disk without the Keychain.45public final class DiskCache: Sendable {46 public let directory: URL47 private let key: SymmetricKey48 private let io = OSAllocatedUnfairLock(initialState: ())4950 public init(directory: URL, key: SymmetricKey) throws {51 self.directory = directory; self.key = key52 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])53 var values = URLResourceValues(); values.isExcludedFromBackup = true54 var d = directory; try? d.setResourceValues(values)55 }5657 private struct Envelope<T: Codable>: Codable { var fetchedAt: Date; var value: T }5859 private func file(_ key: String) -> URL {60 let h = SHA256.hash(data: Data(key.utf8)).prefix(16).map { String(format: "%02x", $0) }.joined()61 return directory.appendingPathComponent(h + ".vqc")62 }6364 public func write<T: Codable>(_ value: T, for cacheKey: String, at date: Date = Date()) {65 guard let plain = try? JSONEncoder().encode(Envelope(fetchedAt: date, value: value)),66 let sealed = try? AES.GCM.seal(plain, using: key, authenticating: Data(cacheKey.utf8)).combined else { return }67 io.withLock { try? sealed.write(to: file(cacheKey), options: [.atomic, .completeFileProtectionUnlessOpen]) }68 }6970 public func read<T: Codable>(_ type: T.Type, for cacheKey: String) -> (value: T, fetchedAt: Date)? {71 guard let sealed = io.withLock({ try? Data(contentsOf: file(cacheKey)) }),72 let box = try? AES.GCM.SealedBox(combined: sealed),73 let plain = try? AES.GCM.open(box, using: key, authenticating: Data(cacheKey.utf8)),74 let env = try? JSONDecoder().decode(Envelope<T>.self, from: plain) else { return nil }75 return (env.value, env.fetchedAt)76 }7778 /// Seals arbitrary bytes under the cache key (AES-GCM, bound to `context`). The sync replica of VQuant Next is79 /// stored with this, so it is exactly as unreadable from a copy of the disk as the cache is.80 public func seal(_ plain: Data, context: String) throws -> Data {81 guard let sealed = try AES.GCM.seal(plain, using: key, authenticating: Data(context.utf8)).combined else { throw CocoaError(.coderInvalidValue) }82 return sealed83 }84 public func open(_ sealed: Data, context: String) throws -> Data {85 try AES.GCM.open(try AES.GCM.SealedBox(combined: sealed), using: key, authenticating: Data(context.utf8))86 }8788 public func remove(_ cacheKey: String) { io.withLock { try? FileManager.default.removeItem(at: file(cacheKey)) } }8990 public func removeAll() {91 io.withLock {92 for f in (try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)) ?? [] where f.pathExtension == "vqc" { try? FileManager.default.removeItem(at: f) }93 }94 }9596 public func usage() -> (files: Int, bytes: Int) {97 let files = (try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: [.fileSizeKey])) ?? []98 let sized = files.filter { $0.pathExtension == "vqc" }99 return (sized.count, sized.reduce(0) { $0 + ((try? $1.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0) })100 }101102 /// Network first; on a network failure the last stored value is returned and marked as cached. Any other error103 /// (the server refused, the data is unreadable) is thrown: a refusal is never hidden behind old data.104 public func fetch<T: Codable & Sendable>(_ cacheKey: String, _ load: @Sendable () async throws -> T) async throws -> Cached<T> {105 do {106 let v = try await load()107 let now = Date()108 write(v, for: cacheKey, at: now)109 return Cached(value: v, fetchedAt: now, fromCache: false)110 } catch let e as APIError where e.kind == .network {111 if let hit = read(T.self, for: cacheKey) { return Cached(value: hit.value, fetchedAt: hit.fetchedAt, fromCache: true) }112 throw e113 }114 }115116 /// The cache encryption key: created once and kept in the Keychain of this Mac.117 public static func keychainKey(service: String) -> SymmetricKey {118 let store = KeychainTokenStore(service: service, account: "cache-key")119 if let s = store.read(), let d = Data(base64Encoded: s), d.count == 32 { return SymmetricKey(data: d) }120 let k = SymmetricKey(size: .bits256)121 try? store.write(k.withUnsafeBytes { Data($0).base64EncodedString() })122 return k123 }124}125