SPB Git

Repository Public

AlertsLogic.swift 7.5 KB 193 lines swift

1import Foundation2import MCCCore34/// Client-side narrowing of the loaded alerts (display only).5struct AlertFilter: Equatable {6    var openOnly = true7    var state: API.AlertState?8    var severity: API.Severity?9    var nodeID: String?10    var text = ""1112    func apply(_ alerts: [API.Alert]) -> [API.Alert] {13        let q = text.trimmingCharacters(in: .whitespaces)14        return alerts.filter { a in15            if openOnly && !a.state.isOpen { return false }16            if let state, a.state != state { return false }17            if let severity, a.severity != severity { return false }18            if let nodeID, a.nodeId != nodeID { return false }19            if !q.isEmpty {20                let hay = [a.summary, a.ruleName, a.nodeAlias ?? "", a.label].joined(separator: " ")21                if !hay.localizedCaseInsensitiveContains(q) { return false }22            }23            return true24        }25    }26}2728/// Table row with non-optional sort keys.29struct AlertRow: Identifiable {30    let alert: API.Alert31    var id: String { alert.id }32    var severityRank: Int { alert.severity.rank }33    var stateRank: Int { [.firing, .pending, .acknowledged, .resolved].firstIndex(of: alert.state) ?? 9 }34    var node: String { alert.nodeAlias ?? "" }35    var rule: String { alert.ruleName }36    var summary: String { alert.summary }37    var started: Date { alert.startedAt }38    var lastValue: Double { alert.lastValue ?? -.infinity }39    var flaps: Int { alert.flapCount }40    var suppressed: String { alert.suppressedBy?.rawValue ?? "" }41}4243struct IncidentRow: Identifiable {44    let incident: API.Incident45    var id: String { incident.id }46    var severityRank: Int { incident.severity.rank }47    var stateRank: Int { [.open, .mitigated, .resolved].firstIndex(of: incident.state) ?? 9 }48    var title: String { incident.title }49    var opened: Date { incident.openedAt }50    var owner: String { incident.ownerDisplayName ?? "" }51    var alerts: Int { incident.alertCount }52}5354/// Scope editor state shared by silences and rules.55struct ScopeDraft: Equatable {56    enum Mode: String, CaseIterable, Identifiable { case all, nodes, tags; var id: String { rawValue } }57    var mode: Mode = .all58    var nodeIDs: Set<String> = []59    var tagsText = ""6061    init() {}62    init(_ scope: API.AlertScope) {63        if let ids = scope.nodeIds, !ids.isEmpty { mode = .nodes; nodeIDs = Set(ids) }64        else if let tags = scope.tags, !tags.isEmpty { mode = .tags; tagsText = tags.joined(separator: ", ") }65        else { mode = .all }66    }6768    var scope: API.AlertScope {69        switch mode {70        case .all: API.AlertScope(all: true)71        case .nodes: API.AlertScope(nodeIds: nodeIDs.sorted())72        case .tags: API.AlertScope(tags: TagList.parse(tagsText))73        }74    }7576    var isComplete: Bool {77        switch mode {78        case .all: true79        case .nodes: !nodeIDs.isEmpty80        case .tags: !TagList.parse(tagsText).isEmpty81        }82    }8384    static func describe(_ scope: API.AlertScope, alias: (String) -> String?) -> String {85        if let ids = scope.nodeIds, !ids.isEmpty { return ids.map { alias($0) ?? String($0.prefix(8)) }.sorted().joined(separator: ", ") }86        if let tags = scope.tags, !tags.isEmpty { return tags.map { "#\($0)" }.joined(separator: " ") }87        return Localization.shared.string("alerts.scope.all")88    }89}9091/// Editing state of an alert rule. Only completeness is checked here; validity is the server's.92struct RuleDraft: Equatable {93    var name = ""94    var description = ""95    var enabled = true96    var kind: API.AlertRuleKind = .threshold97    var metric = ""98    var labelMatch = ""99    var op: API.AlertOp = .gt100    var threshold = ""101    var clearThreshold = ""102    var forSeconds = "60"103    var clearSeconds = "60"104    var severity: API.Severity = .warning105    var scope = ScopeDraft()106    var notify = true107108    init() {}109    init(_ r: API.AlertRule) {110        name = r.name; description = r.description; enabled = r.enabled; kind = r.kind111        metric = r.metric ?? ""; labelMatch = r.labelMatch ?? ""; op = r.op ?? .gt112        threshold = r.threshold.map { Self.text($0) } ?? ""113        clearThreshold = r.clearThreshold.map { Self.text($0) } ?? ""114        forSeconds = String(r.forSeconds); clearSeconds = String(r.clearSeconds)115        severity = r.severity; scope = ScopeDraft(r.scope); notify = r.notify116    }117118    static func text(_ v: Double) -> String { v.rounded() == v ? String(Int64(v)) : String(v) }119120    /// Names of the fields still missing for this kind of rule.121    var missing: [String] {122        var m: [String] = []123        if name.trimmingCharacters(in: .whitespaces).isEmpty { m.append("name") }124        if kind == .threshold {125            if metric.trimmingCharacters(in: .whitespaces).isEmpty { m.append("metric") }126            if parseNumber(threshold) == nil { m.append("threshold") }127            if !clearThreshold.trimmingCharacters(in: .whitespaces).isEmpty, parseNumber(clearThreshold) == nil { m.append("clear_threshold") }128        }129        if parseSeconds(forSeconds) == nil { m.append("for_seconds") }130        if parseSeconds(clearSeconds) == nil { m.append("clear_seconds") }131        if !scope.isComplete { m.append("scope") }132        return m133    }134135    var isComplete: Bool { missing.isEmpty }136137    private var trimmedLabel: String? {138        let l = labelMatch.trimmingCharacters(in: .whitespaces)139        return l.isEmpty ? nil : l140    }141142    var input: API.AlertRuleInput {143        let threshold_ = kind == .threshold144        return API.AlertRuleInput(145            name: name.trimmingCharacters(in: .whitespaces), description: description, enabled: enabled, kind: kind,146            metric: threshold_ ? metric.trimmingCharacters(in: .whitespaces) : nil, labelMatch: trimmedLabel,147            op: threshold_ ? op : nil, threshold: threshold_ ? parseNumber(threshold) : nil,148            clearThreshold: threshold_ ? parseNumber(clearThreshold) : nil,149            forSeconds: parseSeconds(forSeconds), clearSeconds: parseSeconds(clearSeconds),150            severity: severity, scope: scope.scope, notify: notify)151    }152153    /// The kind of an existing rule cannot change (it is not part of the update request).154    var update: API.UpdateAlertRuleRequest {155        let threshold_ = kind == .threshold156        return API.UpdateAlertRuleRequest(157            name: name.trimmingCharacters(in: .whitespaces), description: description, enabled: enabled,158            metric: threshold_ ? metric.trimmingCharacters(in: .whitespaces) : nil, labelMatch: trimmedLabel,159            op: threshold_ ? op : nil, threshold: threshold_ ? parseNumber(threshold) : nil,160            clearThreshold: threshold_ ? parseNumber(clearThreshold) : nil,161            forSeconds: parseSeconds(forSeconds), clearSeconds: parseSeconds(clearSeconds),162            severity: severity, scope: scope.scope, notify: notify)163    }164}165166extension API.AlertOp {167    var symbol: String {168        switch self {169        case .gt: ">"170        case .gte: "≥"171        case .lt: "<"172        case .lte: "≤"173        }174    }175}176177extension API.AlertRuleKind {178    var label: String { Localization.shared.string("rules.kind." + rawValue) }179}180181extension API.AlertRule {182    /// "cpu.usage > 90 for 5 min".183    var conditionText: String {184        switch kind {185        case .threshold:186            let t = threshold.map { RuleDraft.text($0) } ?? "?"187            return "\(metric ?? "?") \(op?.symbol ?? "?") \(t) · \(Format.duration(seconds: Double(forSeconds)))"188        case .absence, .serviceState:189            return "\(kind.label) · \(Format.duration(seconds: Double(forSeconds)))"190        }191    }192}193
Files main
Menu

Theme