Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: App/QuantStore.swift3// Description: Observable state of the Quant Lab: catalogue, jobs, polling.4import AppKit5import SwiftUI6import UserNotifications7import VQuantCore8910// MARK: - Quantitative computations1112@Observable final class QuantStore {13 private(set) var catalogue: QuantCatalogue?14 private(set) var jobs: [QuantJob] = []15 private(set) var details: [String: QuantJob] = [:]16 private(set) var fromCache = false17 private(set) var error: String?18 private(set) var fetchedAt: Date?1920 @ObservationIgnored private let api: VQuantAPI21 @ObservationIgnored private let cache: DiskCache22 @ObservationIgnored private let settings: SettingsStore23 @ObservationIgnored var toasts: ToastCenter?24 @ObservationIgnored private var poll: Task<Void, Never>?25 @ObservationIgnored private var wasRunning: Set<String> = []26 /// When the sync stream last announced a quant job change. While hints arrive the list is refreshed by them27 /// (AppEnvironment.start) and the poll below is only a slow fallback.28 @ObservationIgnored private var lastHint: Date?29 func hintHeard() { lastHint = Date() }3031 init(api: VQuantAPI, cache: DiskCache, settings: SettingsStore) { self.api = api; self.cache = cache; self.settings = settings }32 func reset() { catalogue = nil; jobs = []; details = [:]; error = nil; wasRunning = [] }3334 var runningCount: Int { jobs.filter { $0.status == .running }.count }35 func tool(_ id: String) -> QuantTool? { catalogue?.tools.first { $0.id == id } }3637 func refresh() async {38 do {39 if catalogue == nil { catalogue = try await cache.fetch("quant-tools") { [api] in try await api.quantCatalogue() }.value }40 let r = try await cache.fetch("quant-jobs") { [api] in try await api.quantJobs().jobs }41 let finished = r.value.filter { wasRunning.contains($0.id) && $0.status != .running }42 jobs = r.value; fromCache = r.fromCache; fetchedAt = r.fetchedAt; error = nil43 wasRunning = Set(r.value.filter { $0.status == .running }.map(\.id))44 for j in finished {45 details[j.id] = nil46 if settings.notifyOnCompletion, !NSApp.isActive {47 Notifier.post(title: j.status == .done ? "Computation finished" : j.status == .cancelled ? "Computation cancelled" : "Computation failed", body: "\(tool(j.tool)?.title ?? j.tool) · \(j.subject)", id: j.id, route: .quantJob(j.id))48 }49 }50 } catch { if !(error is CancellationError) { self.error = error.localizedDescription } }51 }5253 /// Submits a computation; the server runs it and this call returns as soon as the job exists.54 func submit(tool: String, params: [String: JSONValue]) async throws -> QuantJob {55 let j = try await api.submitQuantJob(tool: tool, params: params)56 jobs.insert(j, at: 0); wasRunning.insert(j.id)57 return j58 }5960 /// The full record of a job (parameters, code, result). Finished jobs are immutable and are kept for offline reading.61 func detail(_ id: String) async -> QuantJob? {62 if let d = details[id], d.status != .running { return d }63 do {64 let j: QuantJob65 if let hit = cache.read(QuantJob.self, for: "quant-job-\(id)")?.value, hit.status != .running { j = hit }66 else { j = try await api.quantJob(id); if j.status != .running { cache.write(j, for: "quant-job-\(id)") } }67 details[id] = j68 return j69 } catch { toasts?.error(error); return details[id] }70 }7172 func delete(_ id: String) async {73 do { try await api.deleteQuantJob(id); jobs.removeAll { $0.id == id }; details[id] = nil; cache.remove("quant-job-\(id)") }74 catch { toasts?.error(error) }75 }7677 func startPolling() {78 poll?.cancel()79 poll = Task { [weak self] in80 while !Task.isCancelled {81 guard let self else { return }82 if NSApp.isActive || self.runningCount > 0 { await self.refresh() }83 let hintsAlive = self.lastHint.map { Date().timeIntervalSince($0) < 180 } ?? false84 try? await Task.sleep(for: .seconds(self.runningCount > 0 ? (hintsAlive ? 20 : max(2, self.settings.jobPoll)) : 45))85 }86 }87 }88 func stopPolling() { poll?.cancel(); poll = nil }89}90