SPB Git

Repository Public

OpsMonitorModel.swift 5.3 KB 107 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Alerts/OpsMonitorModel.swift3// Description: The read-only monitoring data: capital, PnL, exposure, the three risk books, system health and the quote engine's statistics. Every section is read on its own, keeps its own date and its own failure: one failed read never blanks or zeroes the others, and a section that could not be refreshed keeps its last value marked as stale.4import Foundation5import SPWalletCore67/// One independently loaded block of the monitoring screen.8struct OpsSection<T: Sendable>: Sendable {9    var value: T?10    /// When the app received `value`.11    var fetchedAt: Date?12    /// The last read failed; `value` (if any) is the previous successful read.13    var error: String?14    var loading = false15    var isStale: Bool { value != nil && error != nil }16}1718@MainActor @Observable final class OpsMonitorModel {19    let model: AppModel20    private let monitor: MonitorAPI21    private let dashboard: DashboardAPI2223    private(set) var capital = OpsSection<MonitorCapital>()24    private(set) var pnl = OpsSection<MonitorPnl>()25    private(set) var exposure = OpsSection<MonitorExposure>()26    private(set) var health = OpsSection<MonitorHealth>()27    private(set) var quotes = OpsSection<QuoteStreamStats>()28    private(set) var summary = OpsSection<DashboardSummary>()29    private(set) var refreshing = false3031    init(model: AppModel) { self.model = model; monitor = MonitorAPI(model.client); dashboard = DashboardAPI(model.client) }3233    func refresh() async {34        guard !refreshing else { return }35        refreshing = true; defer { refreshing = false }36        async let a: Void = reloadCapital()37        async let b: Void = reloadPnl()38        async let c: Void = reloadExposure()39        async let e: Void = reloadHealth()40        async let f: Void = reloadQuotes()41        async let g: Void = reloadSummary()42        _ = await (a, b, c, e, f, g)43    }4445    func reloadCapital() async { let m = monitor; await load(\.capital) { try await m.capital() } }46    func reloadPnl() async { let m = monitor; await load(\.pnl) { try await m.pnl() } }47    func reloadExposure() async { let m = monitor; await load(\.exposure) { try await m.exposure() } }48    func reloadHealth() async { let m = monitor; await load(\.health) { try await m.health() } }49    func reloadQuotes() async { let m = monitor; await load(\.quotes) { try await m.quoteStreamStats() } }50    func reloadSummary() async { let d = dashboard; await load(\.summary) { try await d.summary() } }5152    private func load<T: Sendable>(_ path: ReferenceWritableKeyPath<OpsMonitorModel, OpsSection<T>>, _ call: @Sendable () async throws -> T) async {53        self[keyPath: path].loading = true54        do {55            let v = try await call()56            self[keyPath: path] = OpsSection(value: v, fetchedAt: Date(), error: nil, loading: false)57        } catch {58            self[keyPath: path].error = model.describe(error)59            self[keyPath: path].loading = false60        }61    }62}6364enum OpsText {65    /// Reason codes of a failed dashboard section. The server's message is for logs; the screen shows the code's meaning.66    static func sectionError(_ code: String) -> String {67        switch code {68        case "timeout": "La source n’a pas répondu à temps."69        case "source_failed": "La source a échoué."70        default: "La source a répondu par une erreur (\(code))."71        }72    }73    static func connectorGroup(_ g: String) -> String {74        switch g {75        case "signer": "Signataire"; case "rpc": "RPC des réseaux"; case "market": "Données de marché"; case "venue": "Plateformes"76        case "swap": "Échange"; case "bridge": "Ponts"; case "database": "Base de données"; default: g77        }78    }79    static func capability(_ id: String) -> String {80        switch id {81        case "deriv_live_mainnet": "Dérivés réels sur réseau principal"82        case "deriv_mandate_mainnet": "Trading autonome (mandat) sur réseau principal"83        case "deriv_gmx_live": "Ordres GMX v2 réels"84        case "trading_api_execution": "Exécution par le service d’ordres"85        case "deriv_mm_mainnet": "Tenue de marché sur réseau principal"86        case "deriv_mm_testnet": "Tenue de marché sur testnet"87        case "research_runner": "Exécuteur de recherche (jobs IA)"88        case "research_readonly_db": "Base en lecture seule pour les backtests"89        case "broadcast": "Diffusion des transactions signées"90        case "workers": "Boucles d’arrière-plan"91        case "strategy_sandbox_enforced": "Confinement du code de stratégie"92        case "web_app": "App web servie par ce processus"93        case "market_data_apibricks": "Seconde source de prix (API Bricks)"94        default: id95        }96    }97    static func agentState(_ s: String) -> String {98        switch s {99        case "DRAFT": "Brouillon"; case "BACKTESTING": "Backtest"; case "PAPER_TRADING": "Papier"; case "LIVE": "Réel"; case "PAUSED": "En pause"100        case "STOPPED": "Arrêté"; case "RESEARCH": "Recherche"; default: s101        }102    }103    static func venueState(_ s: StreamVenueState) -> String {104        switch s { case .connected: "Connectée"; case .reconnecting: "Reconnexion"; case .stale: "Périmée"; case .down: "En panne"; case .idle: "Au repos"; case .unknown(let r): r }105    }106}107
Files main
Menu

Theme