SPB Git

Repository Public

Stores.swift 11.0 KB 232 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: App/Stores.swift3// Description: Observable state shared by every window: quotes with their freshness, watchlists, the agent workspace, saved layouts, toasts, figures.4import AppKit5import SwiftUI6import VQuantCore78// MARK: - Toasts910@Observable final class ToastCenter {11    struct Toast: Identifiable, Equatable { let id = UUID(); var text: String; var isError: Bool }12    private(set) var current: Toast?13    @ObservationIgnored private var task: Task<Void, Never>?1415    func show(_ text: String, error: Bool = false) {16        current = Toast(text: text, isError: error)17        task?.cancel()18        task = Task { try? await Task.sleep(for: .seconds(error ? 6 : 3)); if !Task.isCancelled { current = nil } }19    }20    func error(_ e: Error) { if !(e is CancellationError) { show(e.localizedDescription, error: true) } }21}2223// MARK: - Market data2425/// A quote with what is known about its age. `fromCache` means the server could not be reached and this is the last26/// value this Mac received.27struct QuoteEntry: Equatable {28    var quote: Quote29    var receivedAt: Date30    var fromCache: Bool31    var freshness: Freshness { fromCache ? .cached(fetched: receivedAt) : .ofQuote(asOf: quote.asOf, now: Date()) }32}3334@Observable final class MarketStore {35    private(set) var quotes: [String: QuoteEntry] = [:]36    /// Symbols the provider has no quote for (unknown ticker): shown as unavailable, never retried in a loop.37    private(set) var unknown: Set<String> = []38    private(set) var indices: [QuoteEntry] = []39    private(set) var movers: [Mover: [Quote]] = [:]40    private(set) var moversFetched: Date?41    private(set) var hours: [ExchangeHours] = []42    private(set) var lastError: String?43    private(set) var lastSuccess: Date?44    private(set) var refreshing = false4546    @ObservationIgnored private let api: VQuantAPI47    @ObservationIgnored private let cache: DiskCache48    @ObservationIgnored private let settings: SettingsStore49    @ObservationIgnored var connectivity: Connectivity?50    @ObservationIgnored private var interest: [String: Int] = [:]51    @ObservationIgnored private var loop: Task<Void, Never>?5253    init(api: VQuantAPI, cache: DiskCache, settings: SettingsStore) { self.api = api; self.cache = cache; self.settings = settings }5455    func start() {56        loop?.cancel()57        loop = Task { [weak self] in58            while !Task.isCancelled {59                guard let self else { return }60                // polling pauses while the app is in the background or the Mac is offline (low idle CPU, no pointless requests)61                if NSApp.isActive || self.lastSuccess == nil { await self.refresh() }62                let every = self.settings.quoteRefresh63                try? await Task.sleep(for: .seconds(every > 0 ? every : 3600))64            }65        }66    }67    func stop() { loop?.cancel(); loop = nil }68    func reset() { quotes = [:]; indices = []; movers = [:]; hours = []; unknown = []; lastError = nil; lastSuccess = nil; interest = [:] }6970    /// Views declare the symbols they show; only those are polled.71    func watch(_ symbols: [String]) {72        var fresh: [String] = []73        for s in symbols { interest[s, default: 0] += 1; if quotes[s] == nil, !unknown.contains(s) { fresh.append(s) } }74        if !fresh.isEmpty { Task { await fetch(fresh) } }75    }76    func unwatch(_ symbols: [String]) { for s in symbols { if let n = interest[s] { interest[s] = n > 1 ? n - 1 : nil } } }7778    func refresh() async {79        guard !refreshing else { return }80        refreshing = true; defer { refreshing = false }81        async let i: Void = loadIndices()82        async let q: Void = fetch(Array(interest.keys))83        _ = await (i, q)84    }8586    private func loadIndices() async {87        do {88            let r = try await cache.fetch("indices") { [api] in try await api.indices() }89            indices = r.value.map { QuoteEntry(quote: $0, receivedAt: r.fetchedAt, fromCache: r.fromCache) }90            if r.fromCache { lastError = "Offline: showing the last values received." } else { lastError = nil; lastSuccess = Date() }91        } catch { if !(error is CancellationError) { lastError = error.localizedDescription } }92    }9394    func loadMovers() async {95        for m in Mover.allCases {96            if let r = try? await cache.fetch("movers-\(m.rawValue)", { [api] in try await api.movers(m) }) { movers[m] = r.value; moversFetched = r.fetchedAt }97        }98        if let r = try? await cache.fetch("market-hours", { [api] in try await api.marketHours() }) { hours = r.value }99    }100101    func fetch(_ symbols: [String]) async {102        let list = Array(Set(symbols)).filter { !unknown.contains($0) }103        guard !list.isEmpty else { return }104        await withTaskGroup(of: (String, Cached<Quote?>?, String?).self) { group in105            var pending = list[...]106            func add() { if let s = pending.popFirst() { group.addTask { [api, cache] in107                do { return (s, try await cache.fetch("quote-\(s)") { try await api.quote(s) }, nil) }108                catch { return (s, nil, error is CancellationError ? nil : error.localizedDescription) }109            } } }110            for _ in 0..<6 { add() }   // at most six requests in flight111            for await (s, r, err) in group {112                if let r {113                    if let q = r.value { quotes[s] = QuoteEntry(quote: q, receivedAt: r.fetchedAt, fromCache: r.fromCache) }114                    else { unknown.insert(s); quotes[s] = nil }115                    if !r.fromCache { lastSuccess = Date() }116                } else if let err { lastError = err }117                add()118            }119        }120    }121122    func entry(_ symbol: String) -> QuoteEntry? { quotes[symbol] ?? indices.first { $0.quote.symbol == symbol } }123124    /// Is the primary US market open, according to the provider's exchange table (nil when it has not been loaded)?125    var usMarketOpen: Bool? { hours.first { $0.exchange == "NASDAQ" }?.isMarketOpen }126}127128// MARK: - Watchlists (local to this Mac)129130@Observable final class WatchlistStore {131    private(set) var lists: [Watchlist]132    @ObservationIgnored private let file: JSONFile<[Watchlist]>133134    init(file: JSONFile<[Watchlist]>) {135        self.file = file136        lists = file.load() ?? [Watchlist(name: "Watchlist", symbols: ["AAPL", "MSFT", "NVDA", "GOOGL", "AMZN", "SPY"])]137    }138    private func save() { try? file.save(lists) }139140    @discardableResult func create(_ name: String) -> Watchlist {141        let w = Watchlist(name: name.trimmingCharacters(in: .whitespaces).isEmpty ? "Watchlist \(lists.count + 1)" : name, symbols: [])142        lists.append(w); save(); return w143    }144    func rename(_ id: UUID, _ name: String) { if let i = lists.firstIndex(where: { $0.id == id }), !name.trimmingCharacters(in: .whitespaces).isEmpty { lists[i].name = name; save() } }145    func delete(_ id: UUID) { lists.removeAll { $0.id == id }; save() }146    @discardableResult func add(_ symbol: String, to id: UUID) -> Bool {147        guard let i = lists.firstIndex(where: { $0.id == id }) else { return false }148        let ok = lists[i].add(symbol); if ok { save() }; return ok149    }150    func remove(_ symbols: Set<String>, from id: UUID) { if let i = lists.firstIndex(where: { $0.id == id }) { lists[i].symbols.removeAll { symbols.contains($0) }; save() } }151    func move(in id: UUID, from: IndexSet, to: Int) { if let i = lists.firstIndex(where: { $0.id == id }) { lists[i].symbols.move(fromOffsets: from, toOffset: to); save() } }152    func list(_ id: UUID?) -> Watchlist? { lists.first { $0.id == id } }153}154155// MARK: - Agent workspace (memory, portfolio, watches) — server state156157@Observable final class WorkspaceStore {158    private(set) var workspace: Workspace?159    private(set) var fetchedAt: Date?160    private(set) var fromCache = false161    private(set) var loading = false162    private(set) var error: String?163    @ObservationIgnored private let api: VQuantAPI164    @ObservationIgnored private let cache: DiskCache165166    init(api: VQuantAPI, cache: DiskCache) { self.api = api; self.cache = cache }167    func reset() { workspace = nil; fetchedAt = nil; error = nil; fromCache = false }168169    var positions: [Position] { workspace?.positions ?? [] }170    /// Writes are refused while the workspace on screen comes from the cache: an edit must apply to the server's state.171    var canEdit: Bool { workspace != nil && !fromCache }172173    func refresh() async {174        loading = true; defer { loading = false }175        do {176            let r = try await cache.fetch("workspace") { [api] in try await api.workspace() }177            workspace = r.value; fetchedAt = r.fetchedAt; fromCache = r.fromCache; error = nil178        } catch { if !(error is CancellationError) { self.error = error.localizedDescription } }179    }180181    /// Runs a change on the server, then reloads: the screen always shows what the server holds.182    func perform(_ change: @escaping (VQuantAPI) async throws -> Void) async throws {183        try await change(api)184        await refresh()185    }186}187188// MARK: - Saved window layouts189190@Observable final class LayoutStore {191    private(set) var saved: [SavedWorkspace]192    @ObservationIgnored private let file: JSONFile<[SavedWorkspace]>193    init(file: JSONFile<[SavedWorkspace]>) { self.file = file; saved = file.load() ?? [] }194    func save(_ w: SavedWorkspace) { saved.removeAll { $0.name == w.name }; saved.insert(w, at: 0); try? file.save(saved) }195    func delete(_ id: UUID) { saved.removeAll { $0.id == id }; try? file.save(saved) }196    /// After the migration to synced `workspace` objects: only the layouts the shared model cannot describe stay here.197    func removeSynced(_ isSynced: (SavedWorkspace) -> Bool) { saved.removeAll(where: isSynced); try? file.save(saved) }198}199200// MARK: - Figures201202/// Figures of reports (`/figures/…png` on the server, fetched with the session) kept in memory for the windows that203/// show them and in the encrypted cache for offline reading.204@Observable final class ImageLoader {205    @ObservationIgnored private let api: VQuantAPI206    @ObservationIgnored private let cache: DiskCache207    @ObservationIgnored private let memory = NSCache<NSString, NSImage>()208    @ObservationIgnored private var inflight: [String: Task<NSImage?, Never>] = [:]209210    init(api: VQuantAPI, cache: DiskCache) { self.api = api; self.cache = cache; memory.countLimit = 80 }211    func reset() { memory.removeAllObjects(); inflight = [:] }212213    func data(_ path: String) async -> Data? {214        if let d = try? await cache.fetch("asset-\(path)", { [api] in try await api.asset(path: path) }) { return d.value }215        return nil216    }217218    func image(_ path: String) async -> NSImage? {219        if let hit = memory.object(forKey: path as NSString) { return hit }220        if let t = inflight[path] { return await t.value }221        let t = Task<NSImage?, Never> { [weak self] in222            guard let self, let d = await self.data(path), let img = NSImage(data: d) else { return nil }223            self.memory.setObject(img, forKey: path as NSString)224            return img225        }226        inflight[path] = t227        let img = await t.value228        inflight[path] = nil229        return img230    }231}232
Files main
Menu

Theme