Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Terminal/TerminalStore.swift3// Description: State of the Terminal on backend 6: the market overview, quotes of the data layer and statements, each read network-first and kept as the raw server answer in the encrypted cache so the last one stays readable offline, marked as cached.4import SwiftUI5import VQuantCore6import VQuantKit78/// A server answer with what is known about its age. `fromCache`: the server could not be reached and this is the9/// last answer this Mac received.10struct TerminalRead<T: Sendable>: Sendable {11 var value: T12 var receivedAt: Date13 var fromCache: Bool14}1516@Observable final class TerminalStore: SessionScoped {17 // market overview18 private(set) var overview: TerminalRead<VQMarketOverview>?19 private(set) var overviewError: String?20 private(set) var overviewLoading = false2122 // quotes of /api/v2/data/quotes23 private(set) var quotes: [String: VQQuote] = [:]24 /// Symbols nobody quoted (the server's `missing`).25 private(set) var missing: Set<String> = []26 private(set) var quotesFreshness: VQFreshness?27 private(set) var quotesReceived: Date?28 private(set) var quotesFromCache = false29 private(set) var quotesError: String?30 private(set) var quotesLoading = false3132 @ObservationIgnored private let client: VQClient33 @ObservationIgnored private let cache: DiskCache34 /// DEBUG launch argument `-VQXTerminalOffline 1`: after its first answer, every read behaves as if the network35 /// were down, so the cached states can be looked at without unplugging the Mac.36 @ObservationIgnored private let simulateOffline: Bool37 @ObservationIgnored private var answered: Set<String> = []3839 init(app: AppEnvironment) {40 client = app.vq.client; cache = app.cache41 simulateOffline = app.options.extra["TerminalOffline"] != nil42 }4344 func reset() {45 overview = nil; overviewError = nil; quotes = [:]; missing = []; quotesFreshness = nil; quotesReceived = nil; quotesFromCache = false; quotesError = nil; answered = []46 }4748 /// Network first; the raw body is kept in the encrypted cache. Only a *network* failure falls back to the last49 /// stored body (a refusal of the server is never hidden behind old data). The body is decoded tolerantly by the50 /// kit's models, so an answer cached by an older version still reads.51 private func read<T: VQJSONDecodable>(_ key: String, _ request: VQRequest, as type: T.Type = T.self) async throws -> TerminalRead<T> {52 do {53 if simulateOffline, answered.contains(key) { throw VQError(.network, message: "Offline (simulated by -VQXTerminalOffline).") }54 let data = try await client.data(request)55 let json: VQJSON56 do { json = try VQJSON.parse(data) } catch { throw VQError(.decoding, status: 200, message: "The server sent an answer that is not JSON (\(request.path)).") }57 let now = Date()58 cache.write(data, for: key, at: now)59 answered.insert(key)60 return TerminalRead(value: T(json: json), receivedAt: now, fromCache: false)61 } catch let e as VQError where e.kind == .network {62 if let hit = cache.read(Data.self, for: key), let json = try? VQJSON.parse(hit.value) {63 return TerminalRead(value: T(json: json), receivedAt: hit.fetchedAt, fromCache: true)64 }65 throw e66 }67 }6869 // MARK: overview7071 func loadOverview() async {72 guard !overviewLoading else { return }73 overviewLoading = true; defer { overviewLoading = false }74 do {75 overview = try await read("v2-market-overview", .get("/api/v2/market/overview", timeout: 60))76 overviewError = nil77 } catch is CancellationError {} catch { if !Task.isCancelled { overviewError = (error as? VQError)?.userMessage ?? error.localizedDescription } }78 }7980 // MARK: quotes8182 /// Quotes of the given symbols (60 per request, the server's limit). Symbols no longer asked for are forgotten.83 func loadQuotes(_ symbols: [String]) async {84 let list = Array(Set(symbols)).sorted()85 guard !list.isEmpty else { return }86 quotesLoading = true; defer { quotesLoading = false }87 var got: [String: VQQuote] = [:], gone: Set<String> = [], cached = false, received: Date?, fresh: VQFreshness?88 do {89 for chunk in stride(from: 0, to: list.count, by: 60).map({ Array(list[$0..<min($0 + 60, list.count)]) }) {90 let r: TerminalRead<VQQuotes> = try await read("v2-quotes-" + chunk.joined(separator: ","), .get("/api/v2/data/quotes", [VQQueryItem("symbols", chunk.joined(separator: ","))]))91 for q in r.value.quotes { got[q.symbol] = q }92 gone.formUnion(r.value.missing)93 cached = cached || r.fromCache; received = r.receivedAt; fresh = r.value.freshness ?? fresh94 }95 for (k, v) in got { quotes[k] = v }96 missing.subtract(got.keys); missing.formUnion(gone)97 quotesFreshness = fresh; quotesReceived = received; quotesFromCache = cached; quotesError = nil98 } catch is CancellationError {} catch { if !Task.isCancelled { quotesError = (error as? VQError)?.userMessage ?? error.localizedDescription } }99 }100101 // MARK: statements102103 func statements(_ symbol: String, period: String, limit: Int) async throws -> TerminalRead<VQStatements> {104 try await read("v2-statements-\(symbol)-\(period)-\(limit)",105 .get("/api/v2/data/statements/\(VQRequest.segment(symbol))", [VQQueryItem("period", period), VQQueryItem("limit", String(limit))], timeout: 60))106 }107}108109extension AppEnvironment {110 var terminal: TerminalStore { store { TerminalStore(app: self) } }111}112