SPB Git

Repository Public

NodesLogic.swift 7.5 KB 148 lines swift

1import Foundation2import MCCCore34/// Filters of the node list. Every criterion is optional; nil means "any".5struct NodeFilter: Equatable, Sendable {6    var freshness: API.Freshness?7    var kind: API.NodeKind?8    var site: String?9    var maintenanceOnly = false10    var isActive: Bool { freshness != nil || kind != nil || site != nil || maintenanceOnly }11    var activeCount: Int { [freshness != nil, kind != nil, site != nil, maintenanceOnly].filter { $0 }.count }12}1314enum NodeSort: String, CaseIterable, Identifiable, Sendable {15    case alias, state, cpu, memory, alerts16    var id: String { rawValue }17    var title: String { trDynamic("nodes.sort." + rawValue) }18}1920/// Pure logic of the node screens (filtering, sorting, selection for comparison, metric naming).21enum NodesLogic {22    static let compareRange = 2...423    static let chartMetrics = ["cpu.usage", "mem.used", "load.1"]2425    static func matches(_ n: API.Node, search: String) -> Bool {26        let q = search.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()27        guard !q.isEmpty else { return true }28        let hay = [n.alias, n.hostname, n.site, n.role, n.environment, n.model ?? "", n.chip ?? "", n.primaryIp ?? ""] + n.tags29        return hay.contains { $0.lowercased().contains(q) }30    }3132    static func matches(_ n: API.Node, filter f: NodeFilter) -> Bool {33        if let x = f.freshness, n.freshness != x { return false }34        if let x = f.kind, n.kind != x { return false }35        if let x = f.site, n.site != x { return false }36        if f.maintenanceOnly, !n.maintenance { return false }37        return true38    }3940    /// Worst first: offline, stale, fresh.41    static func rank(_ f: API.Freshness) -> Int {42        switch f {43        case .offline: 044        case .stale: 145        case .fresh: 246        }47    }4849    static func apply(_ nodes: [API.Node], search: String, filter: NodeFilter, sort: NodeSort) -> [API.Node] {50        let kept = nodes.filter { matches($0, search: search) && matches($0, filter: filter) }51        let byAlias: (API.Node, API.Node) -> Bool = { $0.alias.localizedStandardCompare($1.alias) == .orderedAscending }52        // A missing measurement sorts last: it is unknown, not zero.53        func desc(_ a: Double?, _ b: Double?, _ x: API.Node, _ y: API.Node) -> Bool {54            switch (a, b) {55            case let (l?, r?): return l == r ? byAlias(x, y) : l > r56            case (_?, nil): return true57            case (nil, _?): return false58            case (nil, nil): return byAlias(x, y)59            }60        }61        switch sort {62        case .alias: return kept.sorted(by: byAlias)63        case .state: return kept.sorted { rank($0.freshness) == rank($1.freshness) ? byAlias($0, $1) : rank($0.freshness) < rank($1.freshness) }64        case .cpu: return kept.sorted { desc($0.headline?.cpuUsagePct, $1.headline?.cpuUsagePct, $0, $1) }65        case .memory: return kept.sorted { desc($0.headline?.memUsedPct, $1.headline?.memUsedPct, $0, $1) }66        case .alerts: return kept.sorted { desc($0.openAlerts.map(Double.init), $1.openAlerts.map(Double.init), $0, $1) }67        }68    }6970    static func sites(_ nodes: [API.Node]) -> [String] { Array(Set(nodes.map(\.site))).sorted() }7172    /// Selection for comparison: toggles, never beyond four nodes.73    static func toggle(_ id: String, in selection: [String]) -> [String] {74        if let i = selection.firstIndex(of: id) { var s = selection; s.remove(at: i); return s }75        guard selection.count < compareRange.upperBound else { return selection }76        return selection + [id]77    }78    static func canCompare(_ selection: [String]) -> Bool { compareRange.contains(selection.count) }7980    /// "43 %" or nil: the caller prints "not reported" for nil, never 0.81    static func percentText(_ v: Double?) -> String? { v.map { Format.percent($0, fractionDigits: 0) } }82    static func loadText(_ v: Double?) -> String? { v.map { Format.number($0, fractionDigits: 2) } }8384    /// "disk.used{/}" → ("disk.used", "/").85    static func split(metricKey key: String) -> (name: String, label: String?) {86        guard let open = key.firstIndex(of: "{"), key.hasSuffix("}") else { return (key, nil) }87        let label = String(key[key.index(after: open)..<key.index(before: key.endIndex)])88        return (String(key[..<open]), label.isEmpty ? nil : label)89    }9091    /// Human title of a metric when the catalog of strings has one, the metric's own name otherwise.92    static func metricTitle(_ key: String) -> String {93        let (name, label) = split(metricKey: key)94        let k = "nodes.metric." + name95        let base = Localization.shared.has(k, language: Localization.shared.language) ? trDynamic(k) : name96        return label.map { "\(base) (\($0))" } ?? base97    }9899    /// Whether a chart can be drawn, or which availability to print instead.100    static func chartBlocker(availability: API.Availability?, hasPoints: Bool) -> API.Availability? {101        guard let a = availability, !hasPoints else { return nil }102        return (a == .available || a == .stale) ? nil : a103    }104105    static func healthTone(_ s: API.HealthBucket.StatePayload) -> StatusTone {106        switch s {107        case .up: .ok108        case .degraded: .warning109        case .down: .critical110        case .maintenance: .maintenance111        case .unknown: .neutral112        }113    }114115    /// Seconds spent in each state over the history.116    static func healthTotals(_ items: [API.HealthBucket]) -> [(state: API.HealthBucket.StatePayload, seconds: TimeInterval)] {117        var acc: [API.HealthBucket.StatePayload: TimeInterval] = [:]118        for b in items { acc[b.state, default: 0] += max(0, b.end.timeIntervalSince(b.start)) }119        return API.HealthBucket.StatePayload.allCases.compactMap { s in acc[s].map { (s, $0) } }120    }121122    static func usageRatio(used: Int64?, total: Int64?) -> Double? {123        guard let used, let total, total > 0 else { return nil }124        return Double(used) / Double(total)125    }126}127128/// Keys built at runtime by the group-A screens; a unit test checks that each exists in fr and en.129enum GroupADynamicKeys {130    static var all: [String] {131        NodeSort.allCases.map { "nodes.sort." + $0.rawValue }132            + API.HealthBucket.StatePayload.allCases.map { "nodes.health." + $0.rawValue }133            + ["cpu.usage", "cpu.user", "cpu.system", "load.1", "load.5", "load.15", "mem.used", "mem.total", "mem.wired", "mem.compressed",134               "mem.pressure.level", "mem.available.percent", "swap.used", "swap.total", "disk.used", "disk.total", "disk.read", "disk.write",135               "net.rx", "net.tx", "net.errors", "net.latency", "net.loss", "gpu.usage", "gpu.mem.used", "thermal.pressure", "thermal.temp",136               "power.draw", "battery.charge", "uptime", "procs.count", "agent.cpu", "agent.rss"].map { "nodes.metric." + $0 }137            + API.NetworkInterface.KindPayload.allCases.map { "network.kind." + $0.rawValue }138            + API.TopologyNode.KindPayload.allCases.map { "network.topology.kind." + $0.rawValue }139            + API.TopologyLink.KindPayload.allCases.map { "network.link.kind." + $0.rawValue }140            + API.TopologyLink.StatePayload.allCases.map { "network.link.state." + $0.rawValue }141            + API.ServiceHistoryEntry.KindPayload.allCases.map { "services.history." + $0.rawValue }142            + ServiceSort.allCases.map { "services.sort." + $0.rawValue }143            + ["requests", "tokens_per_s", "ttft", "latency", "queue"].map { "models.metric." + $0 }144            + API.NasTarget.StatePayload.allCases.map { "storage.nas.state." + $0.rawValue }145            + API.Backup.LastStatusPayload.allCases.map { "storage.backup.status." + $0.rawValue }146    }147}148
Files main
Menu

Theme