SPB Git

Repository Public

SystemStateView.swift 22.5 KB 328 lines swift

1// SP Wallet iOS2// File: Features/Alerts/SystemStateView.swift3// Description: « État du système » (read-only): health of the server's connectors and loops, capabilities and locks, capital,4//              PnL, exposure and the live quote stream's statistics. Every block says what its figures are (observed by the5//              server / estimate) and when; real and simulated money are separate blocks, exactly as served — no grand total.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SwiftUI10import SPWalletCore1112/** What a monitoring figure is. Shown next to it, with its date. */13enum MonitorNature {14    /** A state or a counter the server measured itself. */15    case observed16    /** Computed from balances and third-party prices, or a difference between two stored snapshots. */17    case estimate18    var label: String { switch self { case .observed: String(localized: "OBSERVÉ"); case .estimate: String(localized: "ESTIMATION") } }19    var icon: String { switch self { case .observed: "eye.fill"; case .estimate: "function" } }20    var tone: Tone { switch self { case .observed: .info; case .estimate: .warn } }21}2223/** A monitor answer: live, or the dated offline snapshot, or the error — never a blank that looks like zero. */24struct MonitorSlot<T: Codable & Sendable> {25    var value: T?26    var cachedAt: Date?27    var error: Error?28}2930struct SystemStateView: View {31    @Environment(AppModel.self) private var model32    @State private var health = MonitorSlot<MonitorHealth>()33    @State private var capital = MonitorSlot<MonitorCapital>()34    @State private var pnl = MonitorSlot<MonitorPnl>()35    @State private var exposure = MonitorSlot<MonitorExposure>()36    @State private var stream = MonitorSlot<QuoteStreamStats>()37    @State private var loaded = false3839    var body: some View {40        ScrollView {41            LazyVStack(alignment: .leading, spacing: Theme.Space.section) {42                FreshnessBanner()43                if !loaded { ProgressView().frame(maxWidth: .infinity).padding(.top, 40) }44                else {45                    block(String(localized: "Santé"), .observed, health, date: \.asOf, id: "monitor.health") { HealthBlock(h: $0) }46                    block(String(localized: "Capital"), .estimate, capital, date: \.asOf, id: "monitor.capital") { CapitalBlock(c: $0) }47                    block(String(localized: "Résultat (PnL)"), .estimate, pnl, date: \.asOf, id: "monitor.pnl") { PnlBlock(p: $0) }48                    block(String(localized: "Exposition"), .estimate, exposure, date: \.asOf, id: "monitor.exposure") { ExposureBlock(e: $0) }49                    block(String(localized: "Capacités et verrous"), .observed, health, date: \.asOf, id: "monitor.capabilities") { CapabilitiesBlock(h: $0) }50                    block(String(localized: "Flux de cotations"), .observed, stream, date: \.ts, id: "monitor.stream") { StreamBlock(s: $0) }51                }52            }53            .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 16)54            .frame(maxWidth: 900).frame(maxWidth: .infinity)55        }56        .spPage()57        .navigationTitle(String(localized: "État du système")).navigationBarTitleDisplayMode(.inline)58        .task { await load() }59        .refreshable { await load() }60    }6162    private func load() async {63        let api = MonitorAPI(model.env.client)64        async let h = fetch("alerts-monitor-health") { try await api.health() }65        async let c = fetch("alerts-monitor-capital") { try await api.capital() }66        async let p = fetch("alerts-monitor-pnl") { try await api.pnl() }67        async let e = fetch("alerts-monitor-exposure") { try await api.exposure() }68        async let s = fetch("alerts-monitor-stream") { try await api.quoteStreamStats() }69        (health, capital, pnl, exposure, stream) = await (h, c, p, e, s)70        loaded = true71    }7273    private func fetch<T: Codable & Sendable>(_ key: String, _ call: @escaping @Sendable () async throws -> T) async -> MonitorSlot<T> {74        let cache = model.env.cache75        if model.canOperate {76            do { let v = try await call(); await cache.save(v, key: key); return MonitorSlot(value: v) }77            catch let e { let c = await cache.load(T.self, key: key); return MonitorSlot(value: c?.value, cachedAt: c?.savedAt, error: e) }78        }79        let c = await cache.load(T.self, key: key)80        return MonitorSlot(value: c?.value, cachedAt: c?.savedAt, error: c == nil ? APIError(status: 0, code: "offline", message: "offline") : nil)81    }8283    @ViewBuilder private func block<T, V: View>(_ title: String, _ nature: MonitorNature, _ slot: MonitorSlot<T>, date: KeyPath<T, Date>, id: String, @ViewBuilder content: (T) -> V) -> some View {84        VStack(alignment: .leading, spacing: 10) {85            Text(title).font(.spHeadline).foregroundStyle(Theme.ink).accessibilityAddTraits(.isHeader).accessibilityIdentifier(id)86            if let v = slot.value {87                HStack(spacing: 8) {88                    Pill(text: nature.label, tone: nature.tone, icon: nature.icon)89                    Text((slot.cachedAt != nil ? String(localized: "instantané · ") : "") + String(localized: "par le serveur · ") + String(localized: "au \(v[keyPath: date].formatted(date: .abbreviated, time: .standard))"))90                        .font(.system(size: 12)).foregroundStyle(slot.cachedAt != nil ? Theme.warn : Theme.mute)91                }92                content(v)93            }94            if let e = slot.error, slot.value == nil { ErrorNotice(error: e) }95            else if slot.error != nil { Text(String(localized: "Le serveur n’a pas répondu : dernière valeur synchronisée affichée.")).font(.spFootnote).foregroundStyle(Theme.warn) }96        }97        .spCard(padding: 16)98    }99}100101// MARK: shared rows102103private struct StateRow: View {104    let name: String105    var detail: String?106    /** nil = not measured: shown as such, never as healthy. */107    let ok: Bool?108    var okWord = String(localized: "OK")109    var koWord = String(localized: "en panne")110    var body: some View {111        HStack(alignment: .top, spacing: 10) {112            VStack(alignment: .leading, spacing: 2) {113                Text(name).font(.system(size: 14.5, weight: .medium)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)114                if let detail, !detail.isEmpty { Text(detail).font(.system(size: 12)).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true) }115            }116            Spacer(minLength: 8)117            switch ok {118            case true?: Pill(text: okWord, tone: .ok, icon: "checkmark")119            case false?: Pill(text: koWord, tone: .danger, icon: "xmark")120            case nil: Pill(text: String(localized: "non mesuré"), tone: .neutral, icon: "questionmark")121            }122        }123        .padding(.vertical, 5).accessibilityElement(children: .combine)124    }125}126127private struct FigureRow: View {128    let label: String129    /** nil = the server has no figure: « indisponible », never 0. */130    let usd: Double?131    var tag: (String, Tone)?132    var note: String?133    var signed = false134    var body: some View {135        HStack(alignment: .firstTextBaseline, spacing: 8) {136            VStack(alignment: .leading, spacing: 2) {137                HStack(spacing: 6) {138                    Text(label).font(.system(size: 14.5, weight: .medium)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)139                    if let tag { Pill(text: tag.0, tone: tag.1) }140                }141                if let note, !note.isEmpty { Text(note).font(.system(size: 12)).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true) }142            }143            Spacer(minLength: 8)144            if let usd { Masked(text: (signed && usd > 0 ? "+" : "") + Money.fiat(usd, .usd)).font(.system(size: 14.5, weight: .semibold)).monospacedDigit().foregroundStyle(Theme.ink) }145            else { Text(String(localized: "indisponible")).font(.spFootnote).foregroundStyle(Theme.warn) }146        }147        .padding(.vertical, 5).accessibilityElement(children: .combine)148    }149}150151@MainActor private func subhead(_ s: String) -> some View { Text(s).spEyebrow().padding(.top, 6) }152private let realTag: (String, Tone) = (String(localized: "RÉEL"), .danger)153private let paperTag: (String, Tone) = (String(localized: "PAPIER, SIMULÉ"), .neutral)154private let testnetTag: (String, Tone) = (String(localized: "TESTNET"), .info)155156// MARK: blocks157158private struct HealthBlock: View {159    let h: MonitorHealth160    @State private var showConnectors = false161    @State private var showLoops = false162    private func summary(_ title: String, total: Int, bad: Int) -> some View {163        HStack {164            Text(title).font(.system(size: 14.5, weight: .semibold)).foregroundStyle(Theme.ink)165            Spacer(minLength: 8)166            if bad == 0 { Pill(text: String(localized: "\(total) sur \(total) OK"), tone: .ok, icon: "checkmark") }167            else { Pill(text: String(localized: "\(bad) sur \(total) à voir"), tone: .warn, icon: "exclamationmark.triangle.fill") }168        }.accessibilityElement(children: .combine)169    }170    var body: some View {171        VStack(alignment: .leading, spacing: 0) {172            SecurityIndicator(reachable: h.signer.reachable, halted: h.signer.halted).padding(.vertical, 4)173            if !h.signer.reachable { Text(String(localized: "Signataire injoignable : son état d’arrêt est inconnu.")).font(.spFootnote).foregroundStyle(Theme.warn) }174            // long lists fold when nothing is wrong; a failing or unmeasured entry keeps its list open by default175            let badConnectors = h.connectors.filter { $0.ok != true }.count176            DisclosureGroup(isExpanded: $showConnectors) {177              ForEach(h.connectors) { c in178                StateRow(name: c.name, detail: [c.group, c.detail, c.lastSuccessAt.map { String(localized: "dernier succès \(AlertPresentation.age($0))") }].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · "), ok: c.ok)179              }180            } label: { summary(String(localized: "Connecteurs"), total: h.connectors.count, bad: badConnectors) }181            .onAppear { if badConnectors > 0 { showConnectors = true } }182            let badLoops = h.loops.filter { $0.late || ($0.failures ?? 0) > 0 }.count183            DisclosureGroup(isExpanded: $showLoops) {184              ForEach(h.loops) { l in185                StateRow(name: l.name, detail: [l.lastOkAt.map { String(localized: "dernier passage réussi \(AlertPresentation.age($0))") }, l.failures.flatMap { $0 > 0 ? String(localized: "\($0) échec(s)") : nil }, l.lastError].compactMap { $0 }.joined(separator: " · "),186                         ok: !l.late && (l.failures ?? 0) == 0 ? (l.lastOkAt == nil ? nil : true) : false, koWord: l.late ? String(localized: "en retard") : String(localized: "en échec"))187              }188            } label: { summary(String(localized: "Tâches de fond"), total: h.loops.count, bad: badLoops) }189            .onAppear { if badLoops > 0 { showLoops = true } }190            subhead(String(localized: "Intégrité et stockage"))191            StateRow(name: String(localized: "Journal d’audit"), detail: String(localized: "\(h.audit.total) événements") + (h.audit.checkedAt.map { " · " + String(localized: "vérifié \(AlertPresentation.age($0))") } ?? " · " + String(localized: "jamais vérifié")) + (h.audit.brokenAt.map { " · " + String(localized: "rompu à l’événement \($0)") } ?? ""),192                     ok: h.audit.checkedAt == nil ? nil : h.audit.intact, okWord: String(localized: "intact"), koWord: String(localized: "altéré"))193            StateRow(name: String(localized: "Sauvegarde"), detail: h.backup.visible ? (h.backup.lastAt.map { String(localized: "dernière \(AlertPresentation.age($0)) · \(h.backup.files) fichier(s)") } ?? String(localized: "aucune sauvegarde trouvée")) : String(localized: "le serveur ne voit pas le dossier de sauvegarde : rien n’est connu"),194                     ok: h.backup.visible ? h.backup.lastAt != nil : nil, koWord: String(localized: "absente"))195            if let d = h.disk {196                StateRow(name: String(localized: "Disque"), detail: String(localized: "\(d.freeGb.formatted(.number.precision(.fractionLength(1)))) Go libres sur \(d.totalGb.formatted(.number.precision(.fractionLength(0)))) Go (\(d.freePct.formatted(.number.precision(.fractionLength(1)))) %)"), ok: nil)197            } else { StateRow(name: String(localized: "Disque"), detail: String(localized: "le serveur n’a pas pu lire son disque"), ok: nil) }198            if let lab = h.lab {199                StateRow(name: String(localized: "Bac à sable des stratégies"), detail: [lab.mode, lab.reason, lab.lastFailure].compactMap { $0 }.joined(separator: " · "), ok: lab.ok && lab.mode != "off" ? true : false,200                         okWord: String(localized: "confiné"), koWord: lab.mode == "off" ? String(localized: "NON confiné") : String(localized: "indisponible"))201            }202            subhead(String(localized: "Versions"))203            FieldRow(label: String(localized: "API"), value: h.versions.apiVersion + (h.versions.apiCommit.map { " · \($0)" } ?? ""), mono: true)204            if let s = h.versions.startedAt { FieldRow(label: String(localized: "Démarrée"), value: s.formatted(date: .abbreviated, time: .standard)) }205            if let k = h.versions.signerKeyId { FieldRow(label: String(localized: "Clé du signataire"), value: k + (h.versions.signerPolicyVersion.map { " · " + String(localized: "politique v\($0)") } ?? ""), mono: true) }206        }207    }208}209210private struct CapabilitiesBlock: View {211    let h: MonitorHealth212    var body: some View {213        if let caps = h.capabilities, !caps.isEmpty {214            VStack(alignment: .leading, spacing: 0) {215                ForEach(caps) { c in216                    HStack(alignment: .top, spacing: 10) {217                        VStack(alignment: .leading, spacing: 2) {218                            Text(c.id).font(.spMono).foregroundStyle(Theme.ink)219                            if !c.why.isEmpty { Text(c.why).font(.system(size: 12)).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true) }220                            if !c.on, !c.missing.isEmpty { Text(String(localized: "Variables absentes : ") + c.missing.joined(separator: ", ")).font(.system(size: 12, design: .monospaced)).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true) }221                        }222                        Spacer(minLength: 8)223                        Pill(text: c.on ? String(localized: "activée") : String(localized: "verrouillée"), tone: c.on ? .ok : .neutral, icon: c.on ? "checkmark" : "lock.fill")224                    }225                    .padding(.vertical, 6).accessibilityElement(children: .combine)226                }227            }228        } else { Text(String(localized: "Le serveur ne liste aucune capacité.")).font(.spFootnote).foregroundStyle(Theme.mute) }229    }230}231232private struct CapitalBlock: View {233    let c: MonitorCapital234    var body: some View {235        VStack(alignment: .leading, spacing: 0) {236            Text(String(localized: "Trois sortes d’argent, jamais additionnées : le portefeuille (réel, sur chaîne), les agents, les comptes de dérivés. Il n’y a pas de total général."))237                .font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true).padding(.bottom, 4)238            subhead(String(localized: "Portefeuille sur chaîne"))239            FigureRow(label: String(localized: "Valeur estimée"), usd: c.wallet.usd, tag: realTag,240                      note: String(localized: "\(c.wallet.assets) actif(s)") + (c.wallet.unpriced > 0 ? " · " + String(localized: "\(c.wallet.unpriced) sans prix, hors total") : "") + (c.wallet.unavailable > 0 ? " · " + String(localized: "\(c.wallet.unavailable) solde(s) illisible(s), hors total") : "") + (c.wallet.isComplete ? "" : " · " + String(localized: "estimation partielle")))241            subhead(String(localized: "Agents"))242            FigureRow(label: String(localized: "Agents en réel"), usd: c.totals.agentsLiveUsd, tag: realTag)243            FigureRow(label: String(localized: "Agents en papier"), usd: c.totals.agentsPaperUsd, tag: paperTag)244            ForEach(c.agents) { a in245                FigureRow(label: a.name, usd: a.equityUsd, tag: a.real ? realTag : paperTag,246                          note: [a.state, a.network, String(localized: "\(a.positions) position(s)"), a.asOf.map { String(localized: "valeur du \($0.formatted(date: .abbreviated, time: .shortened))") } ?? String(localized: "aucun instantané de valeur"), a.stopReason].compactMap { $0 }.joined(separator: " · "))247            }248            subhead(String(localized: "Comptes de dérivés"))249            FigureRow(label: String(localized: "Plateforme, réseau principal"), usd: c.totals.derivVenueUsd, tag: realTag)250            FigureRow(label: String(localized: "Plateforme, testnet (fonds de test)"), usd: c.totals.derivTestnetUsd, tag: testnetTag)251            FigureRow(label: String(localized: "Papier"), usd: c.totals.derivPaperUsd, tag: paperTag)252            ForEach(c.derivatives) { d in253                FigureRow(label: d.label, usd: d.equity, tag: d.real ? realTag : d.kind == "paper" ? paperTag : testnetTag,254                          note: [d.venue, d.network, String(localized: "\(d.positions) position(s), \(d.openOrders) ordre(s)"), d.halt.map { String(localized: "arrêt : \($0)") }, d.divergence.map { String(localized: "écart : \($0)") }].compactMap { $0 }.joined(separator: " · "))255            }256        }257    }258}259260private struct PnlBlock: View {261    let p: MonitorPnl262    var body: some View {263        VStack(alignment: .leading, spacing: 0) {264            Text(String(localized: "Différence de valeur entre deux instantanés enregistrés (jour selon le fuseau \(p.tz)).") + (p.note == "flows_included" ? " " + String(localized: "Un dépôt ou un retrait dans la fenêtre est compté comme résultat.") : " " + p.note))265                .font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true).padding(.bottom, 4)266            if p.agents.isEmpty, p.derivatives.isEmpty { Text(String(localized: "Aucun agent ni compte de dérivés.")).font(.spFootnote).foregroundStyle(Theme.mute) }267            group(String(localized: "Réel"), p.agents.filter(\.real).map { ($0.id, $0.name, $0.today, $0.d7, $0.d30) } + p.derivatives.filter(\.real).map { ($0.id, $0.label, $0.today, $0.d7, $0.d30) }, tag: realTag)268            group(String(localized: "Simulé (papier, testnet)"), p.agents.filter { !$0.real }.map { ($0.id, $0.name, $0.today, $0.d7, $0.d30) } + p.derivatives.filter { !$0.real }.map { ($0.id, $0.label, $0.today, $0.d7, $0.d30) }, tag: paperTag)269        }270    }271    @ViewBuilder private func group(_ title: String, _ rows: [(String, String, MonitorPnlFigure?, MonitorPnlFigure?, MonitorPnlFigure?)], tag: (String, Tone)) -> some View {272        if !rows.isEmpty {273            subhead(title)274            ForEach(rows, id: \.0) { r in275                VStack(alignment: .leading, spacing: 0) {276                    HStack(spacing: 6) { Text(r.1).font(.system(size: 14.5, weight: .semibold)); Pill(text: tag.0, tone: tag.1) }.padding(.top, 6)277                    figure(String(localized: "Aujourd’hui"), r.2); figure(String(localized: "7 jours"), r.3); figure(String(localized: "30 jours"), r.4)278                }279            }280        }281    }282    private func figure(_ label: String, _ f: MonitorPnlFigure?) -> some View {283        FigureRow(label: label, usd: f?.abs, note: f.map { ($0.partial ? String(localized: "fenêtre partielle, ") : "") + String(localized: "depuis le \($0.from.formatted(date: .abbreviated, time: .shortened))") }, signed: true)284    }285}286287private struct ExposureBlock: View {288    let e: MonitorExposure289    var body: some View {290        VStack(alignment: .leading, spacing: 0) {291            Text(e.caveat == "spot_and_perp_differ" ? String(localized: "Le net est une indication de direction, pas un ratio de couverture : le comptant et les contrats perpétuels sont des instruments différents.") : e.caveat)292                .font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true).padding(.bottom, 4)293            table(String(localized: "Réel"), e.real, tag: realTag)294            table(String(localized: "Simulé (papier, testnet)"), e.simulated, tag: paperTag)295        }296    }297    @ViewBuilder private func table(_ title: String, _ rows: [MonitorExposure.Row], tag: (String, Tone)) -> some View {298        HStack(spacing: 6) { subhead(title); Pill(text: tag.0, tone: tag.1).padding(.top, 6) }299        if rows.isEmpty { Text(String(localized: "Aucune exposition.")).font(.spFootnote).foregroundStyle(Theme.mute).padding(.vertical, 4) }300        ForEach(rows) { r in301            FigureRow(label: r.asset, usd: r.netUsd, note: String(localized: "comptant \(Money.fiat(r.spotUsd, .usd, compact: true)) · long \(Money.fiat(r.perpLongUsd, .usd, compact: true)) · court \(Money.fiat(r.perpShortUsd, .usd, compact: true)) · brut \(Money.fiat(r.grossUsd, .usd, compact: true))") + (r.priced ? "" : " · " + String(localized: "incomplet : une position sans prix")), signed: true)302        }303    }304}305306private struct StreamBlock: View {307    let s: QuoteStreamStats308    var body: some View {309        VStack(alignment: .leading, spacing: 0) {310            row(String(localized: "Connexions ouvertes"), "\(s.connections.open) / \(s.limits.maxConnectionsTotal)")311            row(String(localized: "Connexions refusées"), String(s.connections.refused))312            row(String(localized: "Abonnements"), String(s.subscriptions))313            row(String(localized: "Messages par seconde"), s.messagesPerSec.formatted(.number.precision(.fractionLength(0...1))))314            row(String(localized: "Messages envoyés"), String(s.messagesSent))315            row(String(localized: "Cotations fusionnées (débit)"), String(s.backpressure.conflated))316            row(String(localized: "Transactions de marché abandonnées"), String(s.backpressure.tradesDropped))317            row(String(localized: "Reconnexions en amont"), String(s.upstreamReconnects))318            row(String(localized: "Latence médiane / p95"), s.lagMs.samples == 0 ? String(localized: "non mesurée (aucun échantillon)") : "\(ms(s.lagMs.p50)) / \(ms(s.lagMs.p95))")319            row(String(localized: "Protocole"), "v\(s.protocol)")320        }321    }322    private func ms(_ v: Double?) -> String { v.map { "\($0.formatted(.number.precision(.fractionLength(0)))) ms" } ?? "—" }323    private func row(_ l: String, _ v: String) -> some View {324        HStack { Text(l).font(.system(size: 14.5)).foregroundStyle(Theme.ink); Spacer(minLength: 8); Text(v).font(.system(size: 14.5, weight: .semibold)).monospacedDigit().foregroundStyle(Theme.ink) }325            .padding(.vertical, 5).accessibilityElement(children: .combine)326    }327}328
Files main
Menu

Theme