SPB Git

Repository Public

OverviewView.swift 24.9 KB 487 lines swift

1import MCCCore2import SwiftUI34/// Cluster overview. Two presentations of the same server data: the compact dashboard, and the full-screen5/// "operations centre" with large figures for a wall display.6struct OverviewView: View {7    @Environment(AppModel.self) private var app8    @Environment(\.mccTheme) private var theme910    private var session: AppSession { app.session }1112    var body: some View {13        @Bindable var app = app14        Page(title: tr("nav.overview"), subtitle: subtitle) {15            Toggle(isOn: $app.operationsCentre) { Label(tr("overview.operations_centre"), systemImage: "rectangle.inset.filled") }16                .toggleStyle(.button)17                .help(tr("menu.operations_centre.enter") + " (⇧⌘O)")18                .accessibilityIdentifier("operations-centre-toggle")19        } content: {20            ResourceView(session.cluster.overview) { overview in21                if app.operationsCentre {22                    OperationsCentre(overview: overview)23                } else {24                    dashboard(overview)25                }26            }27        }28        .task(id: app.range) { await load() }29    }3031    private var subtitle: String? {32        session.cluster.overview.value.map { tr("overview.generated_at", Format.time($0.generatedAt, seconds: true)) }33    }3435    private func load() async {36        await session.cluster.overview.loadIfNeeded(maxAge: 10)37        await session.nodes.list.loadIfNeeded()38        async let a: Void = session.can("alerts.read") ? session.alerts.alerts.loadIfNeeded() : ()39        async let m: Void = session.can("maintenance.read") ? session.maintenance.upcoming.loadIfNeeded(maxAge: 60) : ()40        async let t: Void = session.cluster.trends[TrendQuery(metric: "cpu.usage", range: app.range)].loadIfNeeded(maxAge: 30)41        async let u: Void = session.cluster.trends[TrendQuery(metric: "mem.used", range: app.range)].loadIfNeeded(maxAge: 30)42        _ = await (a, m, t, u)43    }4445    private func dashboard(_ o: API.ClusterOverview) -> some View {46        let columns = [GridItem(.adaptive(minimum: 340, maximum: 620), spacing: Tokens.Space.s5, alignment: .top)]47        return LazyVGrid(columns: columns, alignment: .leading, spacing: Tokens.Space.s5) {48            NodesAvailabilityCard(counts: o.nodes)49            CapacityCard(capacity: o.capacity, nodeTotal: o.nodes.total)50            AlertsSummaryCard(alerts: o.alerts, incidents: o.openIncidents)51            WorkloadCard(overview: o)52            StorageSummaryCard(nas: o.nas, backups: o.backups, storage: o.capacity.storage, nodeTotal: o.nodes.total)53            UpcomingMaintenanceCard()54            RecentActionsCard(actions: o.recentActions)55            TrendCard(title: tr("overview.trend.cpu"), query: TrendQuery(metric: "cpu.usage", range: app.range))56            TrendCard(title: tr("overview.trend.memory"), query: TrendQuery(metric: "mem.used", range: app.range))57        }58    }59}6061// MARK: Cards6263struct NodesAvailabilityCard: View {64    @Environment(AppModel.self) private var app65    @Environment(\.mccTheme) private var theme66    let counts: API.NodeCounts6768    var body: some View {69        Card {70            VStack(alignment: .leading, spacing: Tokens.Space.s4) {71                SectionTitle(tr("overview.nodes.title")) { LinkButton(title: tr("overview.see_all")) { app.show(.nodes) } }72                HStack(alignment: .top, spacing: Tokens.Space.s4) {73                    CountTile(value: "\(counts.fresh)", caption: API.Freshness.fresh.label, tone: .ok)74                    CountTile(value: "\(counts.stale)", caption: API.Freshness.stale.label, tone: counts.stale > 0 ? .stale : .neutral)75                    CountTile(value: "\(counts.offline)", caption: API.Freshness.offline.label, tone: counts.offline > 0 ? .offline : .neutral)76                    CountTile(value: "\(counts.maintenance)", caption: tr("overview.nodes.maintenance"), tone: counts.maintenance > 0 ? .maintenance : .neutral)77                }78                Text(tr("overview.nodes.total", counts.total)).font(.caption).foregroundStyle(theme.textTertiary)79                let attention = (app.session.nodes.list.value ?? []).filter { $0.retiredAt == nil && ($0.freshness != .fresh || $0.maintenance) }.prefix(6)80                if !attention.isEmpty {81                    Divider()82                    ForEach(Array(attention), id: \.id) { node in83                        Button { app.openNode(node.id) } label: {84                            HStack {85                                Text(node.alias).font(.callout.weight(.medium)).foregroundStyle(theme.textPrimary)86                                Spacer()87                                if node.maintenance { StatusBadge(tr("overview.nodes.maintenance"), tone: .maintenance, compact: true) }88                                FreshnessLabel(node.freshness, observedAt: node.observedAt ?? node.lastSeenAt).font(.caption)89                            }90                            .contentShape(Rectangle())91                        }92                        .buttonStyle(.plain)93                        .accessibilityHint(tr("overview.open_node"))94                    }95                }96            }97        }98        .accessibilityIdentifier("card-nodes")99    }100}101102struct CapacityCard: View {103    @Environment(\.mccTheme) private var theme104    let capacity: API.ClusterCapacity105    let nodeTotal: Int106107    var body: some View {108        Card {109            VStack(alignment: .leading, spacing: Tokens.Space.s4) {110                SectionTitle(tr("overview.capacity.title"))111                VStack(alignment: .leading, spacing: Tokens.Space.s1) {112                    HStack(alignment: .firstTextBaseline) {113                        Text(tr("overview.capacity.cpu")).font(.callout).foregroundStyle(theme.textSecondary)114                        Spacer()115                        Text(tr("overview.capacity.cores", Int(capacity.cpuCores.total))).font(.callout.weight(.semibold).monospacedDigit()).foregroundStyle(theme.textPrimary)116                    }117                    coverage(capacity.cpuCores)118                }119                meter(tr("overview.capacity.memory"), capacity.memory, binary: true)120                meter(tr("overview.capacity.storage"), capacity.storage, binary: false)121                Text(tr("overview.capacity.note")).font(.caption).foregroundStyle(theme.textTertiary)122            }123        }124        .accessibilityIdentifier("card-capacity")125    }126127    private func coverage(_ c: API.CapacityTotal) -> some View {128        Text(tr("overview.capacity.coverage", c.coverage, nodeTotal))129            .font(.caption)130            .foregroundStyle(c.coverage < nodeTotal ? StatusTone.warning.color(theme) : theme.textTertiary)131    }132133    @ViewBuilder134    private func meter(_ label: String, _ c: API.CapacityTotal, binary: Bool) -> some View {135        VStack(alignment: .leading, spacing: Tokens.Space.s1) {136            UsageMeter(label: label, ratio: c.used.flatMap { c.total > 0 ? Double($0) / Double(c.total) : nil },137                       detail: c.used.map { tr("overview.capacity.used_of", Format.bytes($0, binary: binary), Format.bytes(c.total, binary: binary)) }138                           ?? tr("overview.capacity.total_only", Format.bytes(c.total, binary: binary)))139            coverage(c)140        }141    }142}143144struct AlertsSummaryCard: View {145    @Environment(AppModel.self) private var app146    @Environment(\.mccTheme) private var theme147    let alerts: API.SeverityCounts?148    let incidents: Int?149150    var body: some View {151        Card {152            VStack(alignment: .leading, spacing: Tokens.Space.s4) {153                SectionTitle(tr("overview.alerts.title")) { LinkButton(title: tr("overview.see_all")) { app.show(.alerts) } }154                if let a = alerts {155                    HStack(alignment: .top, spacing: Tokens.Space.s4) {156                        CountTile(value: "\(a.critical)", caption: API.Severity.critical.label, tone: a.critical > 0 ? .critical : .neutral)157                        CountTile(value: "\(a.warning)", caption: API.Severity.warning.label, tone: a.warning > 0 ? .warning : .neutral)158                        CountTile(value: "\(a.info)", caption: API.Severity.info.label, tone: a.info > 0 ? .info : .neutral)159                    }160                } else {161                    NotReported(tr("overview.alerts.not_reported"))162                }163                Divider()164                if let incidents {165                    StatusLabel(tr("overview.incidents.open", incidents), tone: incidents > 0 ? .critical : .ok).font(.callout)166                } else {167                    NotReported(tr("overview.incidents.not_reported"))168                }169                let firing = (app.session.alerts.alerts.value ?? []).filter { $0.state == .firing }.sorted { $0.severity.rank > $1.severity.rank }.prefix(4)170                ForEach(Array(firing), id: \.id) { alert in171                    Button { app.show(.alerts, focus: .alert(alert.id)) } label: {172                        HStack(spacing: Tokens.Space.s2) {173                            Image(systemName: alert.severity.tone.symbol).foregroundStyle(alert.severity.tone.color(theme)).accessibilityHidden(true)174                            Text([alert.nodeAlias, alert.summary].compactMap { $0 }.joined(separator: " — ")).font(.callout).foregroundStyle(theme.textPrimary).lineLimit(1)175                            Spacer(minLength: 0)176                        }177                        .contentShape(Rectangle())178                    }179                    .buttonStyle(.plain)180                    .accessibilityLabel("\(alert.severity.label), \(alert.nodeAlias ?? ""), \(alert.summary)")181                }182            }183        }184        .accessibilityIdentifier("card-alerts")185    }186}187188/// "The server did not report this figure" — never a zero in its place.189struct NotReported: View {190    @Environment(\.mccTheme) private var theme191    let text: String192    init(_ text: String) { self.text = text }193    var body: some View {194        Label(text, systemImage: "questionmark.circle").font(.callout).foregroundStyle(theme.textTertiary)195    }196}197198struct WorkloadCard: View {199    @Environment(AppModel.self) private var app200    @Environment(\.mccTheme) private var theme201    let overview: API.ClusterOverview202203    var body: some View {204        Card {205            VStack(alignment: .leading, spacing: Tokens.Space.s4) {206                SectionTitle(tr("overview.workload.title"))207                row(tr("nav.services"), .services) {208                    if let s = overview.services {209                        HStack(spacing: Tokens.Space.s3) {210                            StatusBadge("\(s.online) \(API.ServiceState.online.label.lowercased())", tone: .ok, compact: true)211                            if s.errored > 0 { StatusBadge("\(s.errored) \(API.ServiceState.errored.label.lowercased())", tone: .critical, compact: true) }212                            if s.stopped > 0 { StatusBadge("\(s.stopped) \(API.ServiceState.stopped.label.lowercased())", tone: .offline, compact: true) }213                            if s.unknown > 0 { StatusBadge("\(s.unknown) \(API.ServiceState.unknown.label.lowercased())", tone: .neutral, compact: true) }214                        }215                    } else { NotReported(tr("overview.not_reported")) }216                }217                row(tr("nav.models"), .models) {218                    if let m = overview.models {219                        Text(tr("overview.models.online", m.online, m.total)).font(.callout.monospacedDigit()).foregroundStyle(theme.textPrimary)220                    } else { NotReported(tr("overview.not_reported")) }221                }222                row(tr("nav.jobs"), .jobs) {223                    if let j = overview.jobs {224                        Text(tr("overview.jobs.counts", j.running, j.queued)).font(.callout.monospacedDigit()).foregroundStyle(theme.textPrimary)225                    } else { NotReported(tr("overview.not_reported")) }226                }227            }228        }229        .accessibilityIdentifier("card-workload")230    }231232    private func row<V: View>(_ title: String, _ item: SidebarItem, @ViewBuilder value: () -> V) -> some View {233        HStack(alignment: .firstTextBaseline) {234            Button(title) { app.show(item) }.buttonStyle(.textLink).font(.callout)235            Spacer()236            value()237        }238        .accessibilityElement(children: .combine)239    }240}241242struct StorageSummaryCard: View {243    @Environment(AppModel.self) private var app244    @Environment(\.mccTheme) private var theme245    let nas: API.NasSummary?246    let backups: API.BackupSummary?247    let storage: API.CapacityTotal248    let nodeTotal: Int249250    var body: some View {251        Card {252            VStack(alignment: .leading, spacing: Tokens.Space.s4) {253                SectionTitle(tr("overview.storage.title")) { LinkButton(title: tr("overview.see_all")) { app.show(.storage) } }254                HStack(alignment: .firstTextBaseline) {255                    Text(tr("overview.storage.nas")).font(.callout).foregroundStyle(theme.textSecondary)256                    Spacer()257                    if let n = nas {258                        if n.total == 0 {259                            Text(tr("overview.storage.nas.none")).font(.callout).foregroundStyle(theme.textTertiary)260                        } else {261                            HStack(spacing: Tokens.Space.s3) {262                                StatusBadge(tr("overview.storage.nas.online", n.online, n.total), tone: n.offline > 0 ? .warning : .ok, compact: true)263                                if n.offline > 0 { StatusBadge(tr("overview.storage.nas.offline", n.offline), tone: .critical, compact: true) }264                                if n.unknown > 0 { StatusBadge(tr("overview.storage.nas.unknown", n.unknown), tone: .neutral, compact: true) }265                            }266                        }267                    } else { NotReported(tr("overview.not_reported")) }268                }269                HStack(alignment: .firstTextBaseline) {270                    Text(tr("overview.storage.backups")).font(.callout).foregroundStyle(theme.textSecondary)271                    Spacer()272                    if let b = backups {273                        if b.total == 0 {274                            Text(tr("overview.storage.backups.none")).font(.callout).foregroundStyle(theme.textTertiary)275                        } else {276                            VStack(alignment: .trailing, spacing: 2) {277                                StatusLabel(tr("overview.storage.backups.counts", b.ok, b.failed, b.unknown), tone: b.failed > 0 ? .critical : .ok).font(.callout)278                                if let t = b.lastSuccessAt { Text(tr("overview.storage.backups.last", Format.relative(t))).font(.caption).foregroundStyle(theme.textTertiary) }279                            }280                        }281                    } else { NotReported(tr("overview.not_reported")) }282                }283            }284        }285        .accessibilityIdentifier("card-storage")286    }287}288289struct UpcomingMaintenanceCard: View {290    @Environment(AppModel.self) private var app291    @Environment(\.mccTheme) private var theme292293    var body: some View {294        Card {295            VStack(alignment: .leading, spacing: Tokens.Space.s4) {296                SectionTitle(tr("overview.maintenance.title")) { LinkButton(title: tr("overview.see_all")) { app.show(.maintenance) } }297                if !app.session.can("maintenance.read") {298                    NotReported(tr("overview.no_permission"))299                } else {300                    let r = app.session.maintenance.upcoming301                    if let list = r.value {302                        let items = list.items.filter { $0.window.status == .scheduled || $0.window.status == .inProgress }.sorted { $0.occurrenceStart < $1.occurrenceStart }.prefix(5)303                        if items.isEmpty {304                            Text(tr("overview.maintenance.none")).font(.callout).foregroundStyle(theme.textSecondary)305                        }306                        ForEach(Array(items), id: \.occurrenceID) { occ in307                            Button { app.show(.maintenance, focus: .maintenanceWindow(occ.window.id)) } label: {308                                HStack(alignment: .firstTextBaseline, spacing: Tokens.Space.s3) {309                                    Image(systemName: occ.window.category.symbol).foregroundStyle(theme.textSecondary).accessibilityHidden(true)310                                    VStack(alignment: .leading, spacing: 1) {311                                        Text(occ.window.title).font(.callout.weight(.medium)).foregroundStyle(theme.textPrimary).lineLimit(1)312                                        Text(Format.dateTime(occ.occurrenceStart) + " · " + tr("overview.maintenance.nodes", occ.window.scope.nodeIds.count))313                                            .font(.caption).foregroundStyle(theme.textSecondary)314                                    }315                                    Spacer(minLength: 0)316                                    if occ.active == true { StatusBadge(API.MaintenanceStatus.inProgress.label, tone: .maintenance, compact: true) }317                                }318                                .contentShape(Rectangle())319                            }320                            .buttonStyle(.plain)321                        }322                    } else if let reason = r.state.unavailableReason {323                        UnavailableInline(reason: reason, error: r.state.error)324                    } else if let e = r.state.error {325                        InlineErrorView(e)326                    } else {327                        ProgressView().controlSize(.small)328                    }329                }330            }331        }332        .accessibilityIdentifier("card-maintenance")333    }334}335336/// One-line version of the unavailable state, for cards.337struct UnavailableInline: View {338    @Environment(\.mccTheme) private var theme339    let reason: UnavailableReason340    let error: APIError?341    var body: some View {342        VStack(alignment: .leading, spacing: 2) {343            Label(text, systemImage: "hammer").font(.callout).foregroundStyle(theme.textSecondary)344            if let c = error?.correlationID { CorrelationIDView(c) }345        }346    }347    private var text: String {348        switch reason {349        case .notImplemented: tr("unavailable.not_implemented.title")350        case .serviceUnavailable: tr("unavailable.service.title")351        case .forbidden: tr("unavailable.forbidden.title")352        case .offline: tr("unavailable.offline.title")353        }354    }355}356357struct RecentActionsCard: View {358    @Environment(AppModel.self) private var app359    @Environment(\.mccTheme) private var theme360    let actions: [API.Action]?361362    var body: some View {363        Card {364            VStack(alignment: .leading, spacing: Tokens.Space.s4) {365                SectionTitle(tr("overview.actions.title")) { LinkButton(title: tr("overview.see_all")) { app.show(.activity) } }366                if let actions {367                    if actions.isEmpty { Text(tr("overview.actions.none")).font(.callout).foregroundStyle(theme.textSecondary) }368                    ForEach(actions.prefix(6), id: \.id) { action in369                        Button { app.openAction(action.id) } label: { ActionRow(action: action) }.buttonStyle(.plain)370                    }371                } else {372                    NotReported(tr("overview.not_reported"))373                }374            }375        }376        .accessibilityIdentifier("card-actions")377    }378}379380struct TrendCard: View {381    @Environment(AppModel.self) private var app382    @Environment(\.mccTheme) private var theme383    let title: String384    let query: TrendQuery385386    var body: some View {387        let resource = app.session.cluster.trends[query]388        Card {389            VStack(alignment: .leading, spacing: Tokens.Space.s3) {390                SectionTitle(title) { Text(query.range.label).font(.caption).foregroundStyle(theme.textTertiary) }391                if let t = resource.value {392                    TimeSeriesChart(title: title, unit: t.unit,393                                    series: t.series.map { ChartSeries(id: $0.group, name: $0.group, metricPoints: $0.points) }, height: 150)394                    if let s = t.series.first {395                        Text(tr("overview.trend.coverage", s.coverage, t.aggregation.rawValue)).font(.caption).foregroundStyle(theme.textTertiary)396                    }397                } else if let reason = resource.state.unavailableReason {398                    UnavailableInline(reason: reason, error: resource.state.error)399                } else if let e = resource.state.error {400                    InlineErrorView(e)401                } else {402                    ProgressView().controlSize(.small).frame(maxWidth: .infinity, minHeight: 150)403                }404            }405        }406    }407}408409// MARK: Operations centre410411/// Large-type presentation for a wall display: the same figures, readable from across a room.412struct OperationsCentre: View {413    @Environment(AppModel.self) private var app414    @Environment(\.mccTheme) private var theme415    let overview: API.ClusterOverview416417    var body: some View {418        VStack(alignment: .leading, spacing: Tokens.Space.s7) {419            HStack(alignment: .top, spacing: Tokens.Space.s7) {420                big("\(overview.nodes.fresh)/\(overview.nodes.total)", tr("overview.ops.nodes_fresh"), overview.nodes.offline > 0 ? .warning : .ok)421                big("\(overview.nodes.offline)", API.Freshness.offline.label, overview.nodes.offline > 0 ? .offline : .neutral)422                if let a = overview.alerts {423                    big("\(a.critical)", API.Severity.critical.label, a.critical > 0 ? .critical : .neutral)424                    big("\(a.warning)", API.Severity.warning.label, a.warning > 0 ? .warning : .neutral)425                } else {426                    big("—", tr("overview.alerts.not_reported"), .neutral)427                }428                if let i = overview.openIncidents { big("\(i)", tr("overview.ops.incidents"), i > 0 ? .critical : .neutral) }429            }430            NodeWall()431            HStack(alignment: .top, spacing: Tokens.Space.s5) {432                TrendCard(title: tr("overview.trend.cpu"), query: TrendQuery(metric: "cpu.usage", range: app.range))433                TrendCard(title: tr("overview.trend.memory"), query: TrendQuery(metric: "mem.used", range: app.range))434            }435        }436        .accessibilityIdentifier("operations-centre")437    }438439    private func big(_ value: String, _ caption: String, _ tone: StatusTone) -> some View {440        VStack(alignment: .leading, spacing: Tokens.Space.s2) {441            HStack(spacing: Tokens.Space.s3) {442                Image(systemName: tone.symbol).font(.title).foregroundStyle(tone.color(theme)).accessibilityHidden(true)443                Text(value).font(.system(.largeTitle, design: .rounded).weight(.bold).monospacedDigit()).foregroundStyle(theme.textPrimary)444            }445            Text(caption).font(.title3).foregroundStyle(theme.textSecondary)446        }447        .frame(maxWidth: .infinity, alignment: .leading)448        .accessibilityElement(children: .ignore)449        .accessibilityLabel(caption)450        .accessibilityValue(value)451    }452}453454/// One tile per node: alias, freshness (icon + text) and headline CPU / memory when measured.455struct NodeWall: View {456    @Environment(AppModel.self) private var app457    @Environment(\.mccTheme) private var theme458459    var body: some View {460        let nodes = (app.session.nodes.list.value ?? []).filter { $0.retiredAt == nil }.sorted { $0.alias.localizedStandardCompare($1.alias) == .orderedAscending }461        LazyVGrid(columns: [GridItem(.adaptive(minimum: 150), spacing: Tokens.Space.s3)], spacing: Tokens.Space.s3) {462            ForEach(nodes, id: \.id) { node in463                let tone: StatusTone = node.maintenance ? .maintenance : node.freshness.tone464                Button { app.openNode(node.id) } label: {465                    VStack(alignment: .leading, spacing: Tokens.Space.s1) {466                        HStack(spacing: Tokens.Space.s2) {467                            Image(systemName: tone.symbol).foregroundStyle(tone.color(theme)).accessibilityHidden(true)468                            Text(node.alias).font(.headline).foregroundStyle(theme.textPrimary).lineLimit(1)469                        }470                        Text(node.maintenance ? tr("overview.nodes.maintenance") : node.freshness.label).font(.caption).foregroundStyle(theme.textSecondary)471                        Text(tr("overview.wall.headline", node.headline?.cpuUsagePct.map { Format.percent($0) } ?? "—",472                                node.headline?.memUsedPct.map { Format.percent($0) } ?? "—"))473                            .font(.caption.monospacedDigit()).foregroundStyle(theme.textTertiary)474                    }475                    .padding(Tokens.Space.s3)476                    .frame(maxWidth: .infinity, alignment: .leading)477                    .background(tone.muted(theme), in: RoundedRectangle(cornerRadius: Tokens.Radius.md))478                    .overlay(RoundedRectangle(cornerRadius: Tokens.Radius.md).strokeBorder(theme.borderSubtle))479                }480                .buttonStyle(.plain)481                .accessibilityLabel(node.alias)482                .accessibilityValue(node.maintenance ? tr("overview.nodes.maintenance") : node.freshness.label)483            }484        }485    }486}487
Files main
Menu

Theme