SPB Git

Repository Public

NodeDetailScreen.swift 16.4 KB 318 lines swift

1import MCCCore2import SwiftUI34/// One node: state, hardware, latest measurements, charts, processes, services, volumes, interfaces, agent.5struct NodeDetailScreen: View {6    @Environment(Navigator.self) private var nav7    @Environment(AppModel.self) private var app8    @Environment(\.mccTheme) private var theme9    @Session private var session10    let nodeID: String1112    private var detail: Resource<API.NodeDetail> { session.nodes.detail[nodeID] }1314    var body: some View {15        @Bindable var app = app16        ScreenStack {17            ResourceSection(resource: detail) { d in18                VStack(alignment: .leading, spacing: Tokens.Space.s5) {19                    header(d)20                    hardware(d)21                    latest(d)22                    SectionCard(tr("nodes.charts")) {23                        RangePicker(range: $app.range)24                        NodeChartsView(nodeID: nodeID, range: app.range)25                    }26                    SectionCard(tr("nodes.health")) { NodeHealthView(nodeID: nodeID, range: app.range) }27                    SectionCard(tr("nodes.processes")) { NodeProcessesView(nodeID: nodeID) }28                    SectionCard(tr("section.services")) { NodeServicesView(nodeID: nodeID) }29                    volumes(d)30                    if !d.interfaces.isEmpty { interfaces(d) }31                    agent(d)32                    RouteRow(route: .nodeNotes(nodeID), identifier: "node-notes") {33                        Label(tr("nodes.notes"), systemImage: "note.text").foregroundStyle(theme.textPrimary)34                    }35                }36            }37        }38        .screen("node-detail", title: detail.value?.node.alias ?? session.nodes.alias(nodeID) ?? tr("nodes.node"),39                load: { await detail.loadIfNeeded() }, reload: reload)40        .navigationBarTitleDisplayMode(.inline)41        .onDisappear { detail.cancelLoad() }42    }4344    private func reload() async {45        async let a: Void = detail.load()46        async let b: Void = session.nodes.metrics[MetricQuery(nodeID: nodeID, metrics: NodesLogic.chartMetrics, range: app.range)].load()47        async let c: Void = session.nodes.processes[nodeID].load()48        async let d: Void = session.nodes.services[nodeID].load()49        async let e: Void = session.nodes.health[HealthQuery(nodeID: nodeID, range: app.range)].load()50        _ = await (a, b, c, d, e)51    }5253    // MARK: Header5455    private func header(_ d: API.NodeDetail) -> some View {56        let n = d.node57        return Card {58            VStack(alignment: .leading, spacing: Tokens.Space.s3) {59                AdaptiveLine(spacing: Tokens.Space.s3) {60                    Label(n.alias, systemImage: n.kind.symbol).font(.title2.weight(.semibold)).foregroundStyle(theme.textPrimary)61                        .accessibilityAddTraits(.isHeader).accessibilityIdentifier("node-alias")62                    StatusBadge(n.kind.label, tone: .neutral, compact: true)63                    if n.maintenance { MaintenanceBadge().accessibilityIdentifier("node-maintenance-badge") }64                }65                FreshnessLine(n.freshness, observedAt: n.observedAt ?? n.lastSeenAt).font(.callout).accessibilityIdentifier("node-freshness")66                if n.maintenance {67                    InfoBanner(tone: .maintenance, title: tr("nodes.maintenance.active"),68                               message: n.maintenanceReason.isEmpty ? tr("nodes.maintenance.no_reason") : n.maintenanceReason)69                    if let w = d.activeMaintenanceWindowId {70                        Button(tr("nodes.maintenance.window")) { nav.go(to: .maintenanceWindow(id: w, occurrence: nil)) }71                            .frame(minHeight: Tokens.Size.touchMin)72                    }73                }74                if let n = n.openAlerts, n > 0 {75                    Button { nav.go(to: .section(.alerts)) } label: { StatusBadge(tr("nodes.open_alerts", n), tone: .warning) }76                        .buttonStyle(.plain).frame(minHeight: Tokens.Size.touchMin)77                }78                AdaptiveLine {79                    HeadlineChip(label: tr("nodes.cpu"), value: NodesLogic.percentText(n.headline?.cpuUsagePct))80                    HeadlineChip(label: tr("nodes.memory"), value: NodesLogic.percentText(n.headline?.memUsedPct))81                    HeadlineChip(label: tr("nodes.disk"), value: NodesLogic.percentText(n.headline?.diskUsedPct))82                    HeadlineChip(label: tr("nodes.load"), value: NodesLogic.loadText(n.headline?.load1))83                }84                InfoRow(tr("nodes.site"), n.site)85                InfoRow(tr("nodes.role"), n.role)86                InfoRow(tr("nodes.environment"), n.environment)87                if !n.tags.isEmpty { InfoRow(tr("nodes.tags"), n.tags.joined(separator: ", ")) }88                MutationButton(title: tr("nodes.actions"), systemImage: "bolt", identifier: "node-actions", prominent: true) {89                    nav.sheet = .actionPicker(target: .init(kind: .node, id: nodeID), targetLabel: n.alias)90                }91            }92        }93    }9495    // MARK: Hardware9697    private func hardware(_ d: API.NodeDetail) -> some View {98        let n = d.node99        return SectionCard(tr("nodes.hardware")) {100            InfoRow(tr("nodes.hw.model"), n.model)101            InfoRow(tr("nodes.hw.chip"), n.chip)102            InfoRow(tr("nodes.hw.arch"), n.arch)103            InfoRow(tr("nodes.hw.cpu_cores"), n.cpuCores.map { Format.integer($0) })104            // Performance levels under the names the machine reports (Super / Performance / Efficiency...).105            ForEach(d.cpuLevels, id: \.self) { level in106                InfoRow(tr("nodes.hw.cpu_level", level.name), tr("nodes.hw.cores", level.cores))107                    .accessibilityIdentifier("node-cpu-level-" + level.name)108            }109            InfoRow(tr("nodes.hw.gpu_cores"), n.gpuCores.map { Format.integer($0) })110            InfoRow(tr("nodes.hw.memory"), n.memBytes.map { Format.bytes($0, binary: true) })111            InfoRow(tr("nodes.hw.storage"), n.storageBytes.map { Format.bytes($0) })112            InfoRow(tr("nodes.hw.os"), [n.osName, n.osVersion, d.osBuild.map { "(\($0))" }].compactMap { $0 }.joined(separator: " "))113            InfoRow(tr("nodes.hw.hostname"), n.hostname)114            // Private identifiers: only when the server returned them (permission nodes.private.read).115            if let v = n.primaryIp { InfoRow(tr("nodes.hw.ip"), v, monospaced: true) }116            if let v = d.serialNumber { InfoRow(tr("nodes.hw.serial"), v, monospaced: true) }117            if let v = d.hardwareUuid { InfoRow(tr("nodes.hw.uuid"), v, monospaced: true) }118            InfoRow(tr("nodes.hw.registered"), Format.dateTime(n.createdAt))119            if let at = d.inventoryAt {120                Text(tr("nodes.hw.inventory_at", Format.dateTime(at))).font(.footnote).foregroundStyle(theme.textTertiary)121            } else {122                Text(tr("nodes.hw.no_inventory")).font(.footnote).foregroundStyle(theme.textTertiary)123            }124        }125    }126127    // MARK: Latest measurements128129    private func latest(_ d: API.NodeDetail) -> some View {130        let values = d.latest.additionalProperties131        return SectionCard(tr("nodes.latest")) {132            if values.isEmpty {133                Text(tr("nodes.latest.none")).font(.callout).foregroundStyle(theme.textSecondary)134            } else {135                TileGrid(minimum: 150) {136                    ForEach(values.keys.sorted(), id: \.self) { key in137                        MetricValueView(NodesLogic.metricTitle(key), value: values[key])138                    }139                }140            }141            FreshnessLine(d.node.freshness, observedAt: d.node.observedAt).font(.footnote)142        }143    }144145    // MARK: Volumes, interfaces, agent146147    private func volumes(_ d: API.NodeDetail) -> some View {148        SectionCard(tr("nodes.volumes")) {149            if d.volumes.isEmpty {150                Text(tr("nodes.volumes.none")).font(.callout).foregroundStyle(theme.textSecondary)151            }152            ForEach(d.volumes, id: \.id) { VolumeRow(volume: $0, showsNode: false) }153        }154    }155156    private func interfaces(_ d: API.NodeDetail) -> some View {157        SectionCard(tr("nodes.interfaces")) {158            ForEach(d.interfaces, id: \.self) { InterfaceRow(interface: $0, showsNode: false) }159        }160    }161162    @ViewBuilder private func agent(_ d: API.NodeDetail) -> some View {163        SectionCard(tr("nodes.agent")) {164            if let a = d.agent {165                if a.revokedAt != nil {166                    InfoBanner(tone: .critical, title: tr("nodes.agent.revoked"), message: a.revokedReason)167                }168                FreshnessLine(a.freshness, observedAt: a.lastSeenAt).font(.callout)169                InfoRow(tr("nodes.agent.version"), a.version)170                InfoRow(tr("nodes.agent.os"), a.os)171                InfoRow(tr("nodes.agent.capabilities"), a.capabilities.isEmpty ? tr("common.none") : a.capabilities.joined(separator: ", "))172                InfoRow(tr("nodes.agent.cert_expiry"), Format.dateTime(a.certNotAfter))173                InfoRow(tr("nodes.agent.cert_serial"), a.certSerial, monospaced: true)174                InfoRow(tr("nodes.agent.enrolled"), Format.dateTime(a.enrolledAt))175                InfoRow(tr("nodes.agent.cpu"), a.overhead?.cpuPct.map { Format.percent($0, fractionDigits: 1) } ?? tr("metric.not_measured"))176                InfoRow(tr("nodes.agent.rss"), a.overhead?.rssBytes.map { Format.bytes($0, binary: true) } ?? tr("metric.not_measured"))177            } else {178                Text(tr(d.node.registeredVia == .manual ? "nodes.agent.manual" : "nodes.agent.none")).font(.callout).foregroundStyle(theme.textSecondary)179            }180        }181    }182}183184/// CPU, memory and load over the selected period. A metric the node cannot provide says why instead of drawing185/// an empty chart.186struct NodeChartsView: View {187    @Environment(\.mccTheme) private var theme188    @Session private var session189    let nodeID: String190    let range: API.TimeRange191192    var body: some View {193        let r = session.nodes.metrics[MetricQuery(nodeID: nodeID, metrics: NodesLogic.chartMetrics, range: range)]194        InlineResource(resource: r) { resp in195            ForEach(NodesLogic.chartMetrics, id: \.self) { metric in196                let series = resp.series.filter { $0.metric == metric }197                let has = series.contains { !$0.points.isEmpty }198                if let blocked = NodesLogic.chartBlocker(availability: resp.availability.additionalProperties[metric], hasPoints: has) {199                    VStack(alignment: .leading, spacing: Tokens.Space.s2) {200                        Text(NodesLogic.metricTitle(metric)).font(.subheadline.weight(.medium)).foregroundStyle(theme.textPrimary)201                        StatusLabel(blocked.label, tone: blocked.tone)202                    }203                    .accessibilityElement(children: .combine)204                    .accessibilityIdentifier("node-chart-unavailable-" + metric)205                } else {206                    TimeSeriesChart(title: NodesLogic.metricTitle(metric), unit: series.first?.unit,207                                    series: series.enumerated().map { i, s in208                                        ChartSeries(id: "\(metric)#\(i)#\(s.label)", name: s.label.isEmpty ? NodesLogic.metricTitle(metric) : s.label, metricPoints: s.points)209                                    },210                                    domain: resp.from < resp.to ? resp.from...resp.to : nil, height: 160)211                    .accessibilityIdentifier("node-chart-" + metric)212                }213            }214        }215        .loads(r, maxAge: 30)216    }217}218219/// Health history: a strip of buckets with a textual summary (the strip alone would be colour only).220struct NodeHealthView: View {221    @Environment(\.mccTheme) private var theme222    @Session private var session223    let nodeID: String224    let range: API.TimeRange225226    var body: some View {227        let r = session.nodes.health[HealthQuery(nodeID: nodeID, range: range)]228        InlineResource(resource: r) { h in229            let totals = NodesLogic.healthTotals(h.items)230            let summary = totals.map { "\(trDynamic("nodes.health." + $0.state.rawValue)) : \(Format.duration(seconds: $0.seconds))" }.joined(separator: ", ")231            InfoRow(tr("nodes.health.uptime"), h.uptimeRatio.map { Format.percent(ratio: $0, fractionDigits: 1) } ?? tr("metric.not_measured"))232            if h.items.isEmpty {233                Text(tr("chart.no_data")).font(.callout).foregroundStyle(theme.textTertiary)234            } else {235                Canvas { ctx, size in236                    guard let t0 = h.items.first?.start, let t1 = h.items.last?.end, t1 > t0 else { return }237                    let span = t1.timeIntervalSince(t0)238                    for b in h.items {239                        let x0 = size.width * b.start.timeIntervalSince(t0) / span240                        let x1 = size.width * b.end.timeIntervalSince(t0) / span241                        let tone = NodesLogic.healthTone(b.state)242                        // Height differs per state as well, so the strip does not rely on colour alone.243                        let hgt = size.height * (b.state == .up ? 1 : b.state == .unknown ? 0.25 : 0.6)244                        ctx.fill(Path(CGRect(x: x0, y: size.height - hgt, width: max(1, x1 - x0 - 0.5), height: hgt)), with: .color(tone.color(theme)))245                    }246                }247                .frame(height: 28)248                .accessibilityElement()249                .accessibilityLabel(tr("nodes.health"))250                .accessibilityValue(summary)251                TileGrid(minimum: 140) {252                    ForEach(totals, id: \.state) { t in253                        StatusLabel("\(trDynamic("nodes.health." + t.state.rawValue)) · \(Format.duration(seconds: t.seconds))", tone: NodesLogic.healthTone(t.state))254                            .font(.footnote)255                    }256                }257            }258        }259        .loads(r, maxAge: 60)260    }261}262263struct NodeProcessesView: View {264    @Environment(\.mccTheme) private var theme265    @Session private var session266    let nodeID: String267268    var body: some View {269        let r = session.nodes.processes[nodeID]270        InlineResource(resource: r) { list in271            if list.availability != .available && list.availability != .stale {272                // Not collected on this node: say so, an empty table would read as "no process".273                StatusLabel(list.availability.label, tone: list.availability.tone).accessibilityIdentifier("node-processes-unavailable")274            } else if list.items.isEmpty {275                Text(tr("nodes.processes.none")).font(.callout).foregroundStyle(theme.textSecondary)276            } else {277                ForEach(list.items, id: \.pid) { p in278                    VStack(alignment: .leading, spacing: Tokens.Space.s1) {279                        AdaptiveLine(spacing: Tokens.Space.s3) {280                            Text(p.name).font(.callout.weight(.medium)).foregroundStyle(theme.textPrimary)281                            Text(tr("nodes.processes.pid", p.pid) + (p.user.map { " · \($0)" } ?? "")).font(.footnote.monospacedDigit()).foregroundStyle(theme.textSecondary)282                        }283                        AdaptiveLine {284                            HeadlineChip(label: tr("nodes.cpu"), value: p.cpuPct.map { Format.percent($0, fractionDigits: 1) })285                            HeadlineChip(label: tr("nodes.memory"), value: p.memBytes.map { Format.bytes($0, binary: true) })286                        }287                    }288                    .frame(maxWidth: .infinity, alignment: .leading)289                    .accessibilityElement(children: .combine)290                    .accessibilityIdentifier("node-process-row")291                    Divider().overlay(theme.borderSubtle)292                }293            }294            FreshnessLine(list.freshness, observedAt: list.observedAt).font(.footnote)295        }296        .loads(r, maxAge: 30)297    }298}299300struct NodeServicesView: View {301    @Environment(\.mccTheme) private var theme302    @Session private var session303    let nodeID: String304305    var body: some View {306        let r = session.nodes.services[nodeID]307        InlineResource(resource: r) { services in308            if services.isEmpty {309                Text(tr("nodes.services.none")).font(.callout).foregroundStyle(theme.textSecondary)310            }311            ForEach(services, id: \.id) { s in312                RouteRow(route: .service(s.id), identifier: "node-service-row-" + s.name) { ServiceRowContent(service: s, showsNode: false) }313            }314        }315        .loads(r, maxAge: 30)316    }317}318
Files main
Menu

Theme