Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Alerts/OpsHealthCards.swift3// Description: System health as the server measures it: signer, connectors, background loops, quote engine, backup, disk, audit chain, strategy sandbox, versions, and the server's optional capabilities — each lock that is off is shown as off with the server's own reason and the names of the settings that close it. A connector that was not measured is "non mesuré", never healthy.4import SwiftUI5import SPWalletCore67struct OpsHealthCards: View {8 let data: OpsMonitorModel910 var body: some View {11 OpsSectionCard(title: "Santé du système", section: data.health, asOf: { $0.asOf }, retry: { Task { await data.reloadHealth() } }) { h in12 OpsSignerRow(signer: h.signer, versions: h.versions)13 Divider()14 OpsConnectors(connectors: h.connectors)15 Divider()16 OpsLoops(loops: h.loops)17 Divider()18 OpsInfra(health: h)19 }20 OpsSectionCard(title: "Capacités du serveur et verrous", section: data.health, asOf: { $0.asOf }, retry: { Task { await data.reloadHealth() } }) { h in21 if let caps = h.capabilities {22 Text("Chaque capacité optionnelle du serveur, avec la raison donnée par le serveur lorsqu’elle est fermée et le nom des réglages qui la ferment (jamais leur valeur). Un verrou fermé n’est pas une panne : c’est l’état voulu tant qu’il n’est pas ouvert sur le serveur.").font(.callout).foregroundStyle(.secondary)23 ForEach(caps) { c in24 HStack(alignment: .top, spacing: 10) {25 Image(systemName: c.on ? "lock.open.fill" : "lock.fill").foregroundStyle(c.on ? Theme.positive : .secondary).frame(width: 18)26 VStack(alignment: .leading, spacing: 1) {27 HStack { Text(OpsText.capability(c.id)).fontWeight(.medium); Text(c.id).font(.caption).foregroundStyle(.secondary); Spacer(); Text(c.on ? "Ouvert" : "Fermé").font(.callout.weight(.medium)).foregroundStyle(c.on ? Theme.positive : .secondary) }28 Text(c.why).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)29 if !c.on, !c.missing.isEmpty { Text("Réglages en cause : \(c.missing.joined(separator: ", "))").font(Theme.monoSmall).foregroundStyle(.secondary) }30 }31 }.padding(.vertical, 3)32 }33 } else { OpsUnavailable(what: "Liste des capacités", reason: "Ce serveur ne la publie pas dans sa réponse de santé.") }34 }35 OpsSectionCard(title: "Moteur de cotations en direct", section: data.quotes, asOf: { $0.ts }, retry: { Task { await data.reloadQuotes() } }) { q in36 OpsQuoteStats(stats: q, summary: data.health.value?.quotes)37 }38 }39}4041private struct OpsOK: View {42 let ok: Bool?43 var body: some View {44 switch ok {45 case true?: Label("OK", systemImage: "checkmark.circle.fill").foregroundStyle(Theme.positive)46 case false?: Label("En panne", systemImage: "xmark.octagon.fill").foregroundStyle(Theme.negative)47 case nil: Label("Non mesuré", systemImage: "questionmark.circle").foregroundStyle(.secondary)48 }49 }50}5152private struct OpsSignerRow: View {53 let signer: SignerReachability54 let versions: MonitorHealth.Versions55 var body: some View {56 HStack(alignment: .top, spacing: 12) {57 Image(systemName: "key.horizontal.fill").foregroundStyle(signer.reachable && signer.halted == false ? Theme.positive : Theme.negative).font(.title3)58 VStack(alignment: .leading, spacing: 2) {59 Text("Signataire isolé").fontWeight(.medium)60 if !signer.reachable { Text("Injoignable : rien ne peut être signé, et son état d’arrêt est inconnu.").foregroundStyle(Theme.negative) }61 else {62 switch signer.halted {63 case true?: Text("Joignable — ARRÊT D’URGENCE ACTIF : il refuse de signer.").foregroundStyle(Theme.negative)64 case false?: Text("Joignable, en service.").foregroundStyle(Theme.positive)65 case nil: Text("Joignable ; état d’arrêt non renvoyé.").foregroundStyle(Theme.warning)66 }67 }68 Text("Clé \(versions.signerKeyId ?? "—") · version de politique \(versions.signerPolicyVersion.map(String.init) ?? "—")").font(.caption).foregroundStyle(.secondary).textSelection(.enabled)69 }70 Spacer()71 }72 }73}7475private struct OpsConnectors: View {76 let connectors: [MonitorConnector]77 var body: some View {78 let failing = connectors.filter { $0.ok == false }.count, unknown = connectors.filter { $0.ok == nil }.count79 VStack(alignment: .leading, spacing: 6) {80 HStack {81 Text("Connecteurs").font(.subheadline.weight(.semibold))82 Text("\(connectors.count - failing - unknown) OK · \(failing) en panne · \(unknown) non mesurés").font(.callout).foregroundStyle(failing > 0 ? Theme.negative : .secondary).monospacedDigit()83 }84 let groups = Dictionary(grouping: connectors, by: \.group)85 ForEach(groups.keys.sorted(), id: \.self) { g in86 DisclosureGroup {87 Grid(alignment: .leading, horizontalSpacing: 14, verticalSpacing: 4) {88 ForEach(groups[g] ?? []) { c in89 GridRow {90 Text(c.name).lineLimit(1)91 OpsOK(ok: c.ok).font(.callout)92 Text(c.lastSuccessAt.map { "dernier succès \(Fmt.relative($0))" } ?? "aucun succès connu").font(.caption).foregroundStyle(.secondary)93 Text(c.detail).font(.caption).foregroundStyle(.secondary).lineLimit(2).textSelection(.enabled)94 }95 }96 }.padding(.leading, 6)97 } label: {98 let list = groups[g] ?? [], bad = list.filter { $0.ok == false }.count, nm = list.filter { $0.ok == nil }.count99 HStack {100 Text(OpsText.connectorGroup(g))101 Spacer()102 Text("\(list.count - bad - nm)/\(list.count) OK\(bad > 0 ? " · \(bad) en panne" : "")\(nm > 0 ? " · \(nm) non mesurés" : "")").font(.callout).foregroundStyle(bad > 0 ? Theme.negative : .secondary).monospacedDigit()103 }104 }105 }106 }107 }108}109110private struct OpsLoops: View {111 let loops: [MonitorLoop]112 var body: some View {113 let late = loops.filter(\.late)114 DisclosureGroup {115 Grid(alignment: .leading, horizontalSpacing: 14, verticalSpacing: 4) {116 GridRow { Text("Boucle"); Text("Cadence"); Text("Dernier succès"); Text("Échecs"); Text("Dernière erreur") }.font(.caption).foregroundStyle(.secondary)117 ForEach(loops) { l in118 GridRow {119 HStack(spacing: 4) { if l.late { Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(Theme.warning) }; Text(l.name).font(Theme.monoSmall) }120 Text(l.everyMs.map { "toutes les \(OpsFmt.duration(ms: $0))" } ?? "—").font(.caption)121 Text(l.lastOkAt.map { Fmt.relative($0) } ?? "jamais").font(.caption).foregroundStyle(l.late ? Theme.warning : .secondary)122 Text(l.failures.map(String.init) ?? "—").monospacedDigit().foregroundStyle((l.failures ?? 0) > 0 ? Theme.warning : .secondary)123 Text(l.lastError.map { "\($0)\(l.lastErrorAt.map { " (\(Fmt.relative($0)))" } ?? "")" } ?? "—").font(.caption).foregroundStyle(.secondary).lineLimit(2).textSelection(.enabled)124 }125 }126 }.padding(.leading, 6)127 } label: {128 HStack {129 Text("Boucles d’arrière-plan").font(.subheadline.weight(.semibold))130 Spacer()131 Text(late.isEmpty ? "\(loops.count) boucles, aucune en retard" : "\(late.count) en retard sur \(loops.count) : \(late.map(\.name).joined(separator: ", "))").font(.callout).foregroundStyle(late.isEmpty ? Color.secondary : Theme.warning)132 }133 }134 }135}136137private struct OpsInfra: View {138 let health: MonitorHealth139 var body: some View {140 let h = health141 VStack(alignment: .leading, spacing: 6) {142 Field(label: "Chaîne d’audit", value: h.audit.intact ? "Intacte — \(h.audit.total) événements, vérifiée \(Fmt.relative(h.audit.checkedAt))" : "ROMPUE à l’événement \(h.audit.brokenAt.map(String.init) ?? "?") (sur \(h.audit.total)) — vérifiée \(Fmt.relative(h.audit.checkedAt))", emphasis: !h.audit.intact)143 Field(label: "Sauvegarde", value: !h.backup.visible ? "Inconnu : le serveur ne voit pas le dossier de sauvegarde (ce n’est pas « aucune sauvegarde »)"144 : h.backup.lastAt.map { "Dernière \(Fmt.relative($0)) (\(Fmt.date($0)))\(h.backup.ageHours.map { " · âge \(OpsFmt.number($0, digits: 1)) h" } ?? "") · \(h.backup.files) fichiers" } ?? "Aucune sauvegarde trouvée dans le dossier (\(h.backup.files) fichiers)")145 Field(label: "Disque du serveur", value: h.disk.map { "\(OpsFmt.number($0.freePct, digits: 1)) % libres — \(OpsFmt.number($0.freeGb, digits: 1)) Go sur \(OpsFmt.number($0.totalGb, digits: 1)) Go (\($0.path))" } ?? "Indisponible : le serveur n’a pas pu lire son disque")146 if let lab = h.lab {147 Field(label: "Bac à sable des stratégies", value: {148 switch lab.mode {149 case "sandbox-exec": lab.ok ? "Confiné (sandbox-exec), opérationnel" : "Confinement en échec : signaux et backtests ne tournent pas\(lab.reason.map { " — \($0)" } ?? "")"150 case "off": "DÉSACTIVÉ (réglage de développement) : le code de stratégie n’est PAS confiné"151 case "unavailable": "Indisponible : rien ne tourne (les agents attendent)\(lab.reason.map { " — \($0)" } ?? "")"152 default: "\(lab.mode)\(lab.ok ? "" : " — en échec")\(lab.reason.map { " — \($0)" } ?? "")"153 }154 }(), emphasis: !lab.ok || lab.mode == "off")155 if lab.calls != nil || lab.refused != nil { Field(label: "Appels au bac à sable", value: "\(lab.calls.map(String.init) ?? "—") appels, \(lab.refused.map(String.init) ?? "—") refusés\(lab.lastFailure.map { " · dernier échec : \($0) (\(Fmt.relative(lab.lastFailureAt)))" } ?? "")") }156 } else { Field(label: "Bac à sable des stratégies", value: "Non renvoyé par ce serveur") }157 if let ab = h.marketData?.apibricks { Field(label: "Source de prix à clé (API Bricks)", value: ab.displayText, mono: true) }158 Field(label: "Version de l’API", value: "\(h.versions.apiVersion)\(h.versions.apiCommit.map { " · commit \($0.prefix(12))" } ?? "") · Node \(h.versions.node) · démarrée \(Fmt.relative(h.versions.startedAt)) (\(Fmt.date(h.versions.startedAt)))")159 }160 }161}162163private struct OpsQuoteStats: View {164 let stats: QuoteStreamStats165 let summary: QuoteEngineSummary?166 var body: some View {167 let q = stats168 LazyVGrid(columns: [GridItem(.adaptive(minimum: 190), spacing: 14)], alignment: .leading, spacing: 10) {169 OpsMini(label: "Connexions ouvertes", value: "\(q.connections.open) (total \(q.connections.total), refusées \(q.connections.refused))")170 OpsMini(label: "Abonnements", value: "\(q.subscriptions)")171 OpsMini(label: "Messages par seconde", value: OpsFmt.number(q.messagesPerSec, digits: 1))172 OpsMini(label: "Messages envoyés", value: "\(q.messagesSent)")173 OpsMini(label: "Octets envoyés", value: ByteCountFormatter.string(fromByteCount: Int64(q.bytesSent), countStyle: .binary))174 OpsMini(label: "Latence (ms) p50 / p95", value: "\(OpsFmt.number(q.lagMs.p50, digits: 0)) / \(OpsFmt.number(q.lagMs.p95, digits: 0)) · \(q.lagMs.samples) mesures")175 OpsMini(label: "Regroupés (conflation)", value: "\(q.backpressure.conflated)")176 OpsMini(label: "Transactions abandonnées", value: "\(q.backpressure.tradesDropped)")177 OpsMini(label: "Resynchronisations de carnet", value: "\(q.backpressure.bookResyncs)")178 OpsMini(label: "Clients lents fermés", value: "\(q.backpressure.slowConsumersClosed)")179 OpsMini(label: "Reconnexions amont", value: "\(q.upstreamReconnects)")180 OpsMini(label: "Tickets émis / utilisés / refusés", value: "\(q.tickets.issued) / \(q.tickets.used) / \(q.tickets.refused)")181 OpsMini(label: "Clients : trames invalides / limités", value: "\(q.clients.badFrames) / \(q.clients.rateLimited)")182 OpsMini(label: "Protocole", value: "v\(q.protocol)")183 }184 Text("Limites du serveur : \(q.limits.maxConnectionsOwner) connexions pour le propriétaire, \(q.limits.maxConnectionsTotal) au total, \(q.limits.maxSubscriptions) abonnements, \(q.limits.maxMessagesPerSec) messages/s par client.").font(.caption).foregroundStyle(.secondary)185 if let venues = summary?.venues, !venues.isEmpty {186 Divider(); Text("Sources amont").font(.subheadline.weight(.semibold))187 Grid(alignment: .leading, horizontalSpacing: 14, verticalSpacing: 4) {188 GridRow { Text("Source"); Text("État"); Text("Âge"); Text("Transport"); Text("Flux"); Text("Reconnexions"); Text("Trous") }.font(.caption).foregroundStyle(.secondary)189 ForEach(venues) { v in190 GridRow {191 Text(v.venue); Text(OpsText.venueState(v.status)).font(.callout).foregroundStyle(v.status == .connected ? Theme.positive : v.status == .idle ? Color.secondary : Theme.warning)192 Text(OpsFmt.duration(ms: v.ageMs)).monospacedDigit(); Text(v.transport).font(.caption)193 Text("\(v.feeds)").monospacedDigit(); Text("\(v.reconnects)").monospacedDigit(); Text("\(v.gaps)").monospacedDigit().foregroundStyle(v.gaps > 0 ? Theme.warning : .primary)194 }195 }196 }197 }198 if let m = stats.metered, !m.isNull {199 DisclosureGroup("Sources à quota (tel que servi)") { Text(OpsJSON.pretty(m)).font(Theme.monoSmall).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading) }200 }201 DisclosureGroup("Diagnostic du concentrateur (tel que servi)") { Text(OpsJSON.pretty(stats.hub)).font(Theme.monoSmall).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading) }202 }203}204