refactor(project): 清理闲置展示链路与重复采样状态

This commit is contained in:
2026-11-09 00:41:09 +08:00
parent 7b3abe37c5
commit b73d51c953
57 changed files with 210 additions and 2822 deletions
View File
+1 -13
View File
@@ -6,9 +6,6 @@ nonisolated struct GPUMetrics: Sendable {
let coreCount: Int?
var renderer: Double? = nil
var tiler: Double? = nil
// Driver accounting, not dedicated VRAM or a capacity denominator.
var inUseMemory: UInt64? = nil
var allocatedMemory: UInt64? = nil
// Independent per-core counters have not been obtained. Never split total usage.
}
@@ -27,21 +24,12 @@ nonisolated enum GPUMonitor {
let cores = (IORegistryEntryCreateCFProperty(service, "gpu-core-count" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() as? NSNumber)?.intValue
devices.append(GPUMetrics(usage: normalized(raw), coreCount: cores.flatMap { $0 > 0 ? $0 : nil },
renderer: normalized((stats?["Renderer Utilization %"] as? NSNumber)?.doubleValue),
tiler: normalized((stats?["Tiler Utilization %"] as? NSNumber)?.doubleValue),
inUseMemory: memoryBytes(stats?["In use system memory"]),
allocatedMemory: memoryBytes(stats?["Alloc system memory"])))
tiler: normalized((stats?["Tiler Utilization %"] as? NSNumber)?.doubleValue)))
}
// Do not average incompatible utilization counters on multi-GPU machines.
return devices.count == 1 ? devices[0] : nil
}
static func memoryBytes(_ raw: Any?) -> UInt64? {
guard let number = raw as? NSNumber else { return nil }
let value = number.doubleValue
guard value.isFinite, value >= 0, value < Double(UInt64.max) else { return nil }
return UInt64(value)
}
static func normalized(_ value: Double?) -> Double? {
value.flatMap { $0.isFinite && (0...100).contains($0) ? $0 / 100 : nil }
}
+6 -10
View File
@@ -17,30 +17,26 @@ nonisolated struct ProcessEnergyMonitor: Sendable {
}
mutating func update(processes: ProcessSnapshot, readings: [ProcessEnergyReading], capability: EnergyCapability, maximumInterval: TimeInterval = 30) -> ProcessEnergySnapshot {
let processesByID = Dictionary(processes.rows.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })
let identities = Set(processes.rows.map(\.id))
var next: [ProcessIdentity: ProcessEnergyReading] = [:]
var usages: [ProcessEnergyUsage] = []
var measured = 0
if capability == .verifiedCPU && !processes.failed {
for reading in readings where next[reading.id] == nil {
guard let process = processesByID[reading.id], reading.status == .available,
guard identities.contains(reading.id), reading.status == .available,
reading.nanojoules != nil, reading.birth > 0, reading.uptime.isFinite else { continue }
next[reading.id] = reading
if let (power, seconds) = Self.watts(current: reading, previous: previous[reading.id], maximumInterval: maximumInterval) {
measured += 1
let usage = ProcessEnergyUsage(process: process, watts: power, seconds: seconds)
usages.append(usage)
usages.append(ProcessEnergyUsage(id: reading.id, watts: power, seconds: seconds))
}
}
}
previous = next // Failed / missing readings invalidate the old baseline.
usages.sort { $0.watts == $1.watts ? $0.id.pid < $1.id.pid : $0.watts > $1.watts }
let state: ProcessEnergySnapshot.State
if capability == .unsupported { state = .unsupported }
else if capability == .unavailable || processes.failed || (capability == .verifiedCPU && next.isEmpty) { state = .unavailable }
else if measured == 0 { state = .waiting }
else { state = measured < processes.enumerated ? .partial : .available }
else if usages.isEmpty { state = .waiting }
else { state = usages.count < processes.enumerated ? .partial : .available }
return ProcessEnergySnapshot(date: Date(), candidates: processes.enumerated, readable: next.count,
measured: measured, rows: usages, state: state)
rows: usages, state: state)
}
}
+4 -11
View File
@@ -24,8 +24,6 @@ actor SystemSampler {
private var batteryTask: Task<Void, Never>?
private var diskCache: DiskHealthMetrics?
private var batteryCache: Double?
private var diskDate: Date?
private var batteryDate: Date?
private var nextDisk: TimeInterval = 0
private var nextBattery: TimeInterval = 0
private let processRead: @Sendable (inout ProcessMonitor) -> ProcessSnapshot
@@ -67,7 +65,7 @@ actor SystemSampler {
// A synchronous OS read may outlive cancellation. Keep the in-flight slot occupied.
}
func sample(includeProcesses: Bool? = nil, includeSlowMetrics: Bool = true, maximumEnergyInterval: TimeInterval = 30, includeEnergy: Bool = true, demandRevision: Int? = nil,
func sample(includeProcesses: Bool? = nil, includeSlowMetrics: Bool = true, maximumEnergyInterval: TimeInterval = 30, demandRevision: Int? = nil,
processUpdate: (@Sendable (ProcessSnapshot) -> Void)? = nil,
energyUpdate: (@Sendable (ProcessEnergySnapshot) -> Void)? = nil) -> MetricsSnapshot {
guard !Task.isCancelled else { return MetricsSnapshot() }
@@ -75,7 +73,7 @@ actor SystemSampler {
setProcessVisible(includeProcesses ?? processVisible, revision: demandRevision)
self.maximumEnergyInterval = min(3600, max(30, maximumEnergyInterval))
self.processUpdate = processUpdate
self.energyUpdate = includeEnergy ? energyUpdate : nil
self.energyUpdate = energyUpdate
if !didProbe {
didProbe = true
if ProcessInfo.processInfo.environment["KYMO_PANEL_PROBE"] == "1" { PanelCapabilityProbe.run() }
@@ -104,7 +102,6 @@ actor SystemSampler {
result.battery = BatteryMonitor.sample()
result.batteryState = result.battery == nil ? BatteryMonitor.availability() : .present
result.gpu = GPUMonitor.sample()
result.gpuUsage = result.gpu?.usage
if includeSlowMetrics && volumeTask == nil && start - volumeSampleTime >= 30 {
volumeTask = Task.detached(priority: .utility) { [self] in
let value = DiskMonitor.volumes()
@@ -120,13 +117,9 @@ actor SystemSampler {
startProcessesIfNeeded()
result.processes = processVisible ? processCache : nil
result.diskHealth = diskCache
result.diskHealthDate = diskDate
result.battery?.health = batteryCache
result.batteryHealthDate = batteryDate
result.volumes = volumes
result.uptime = ProcessInfo.processInfo.systemUptime
var load = [Double](repeating: 0, count: 3)
if getloadavg(&load, 3) == 3 { result.load = load }
if ProcessInfo.processInfo.environment["KYMO_PANEL_PROBE"] == "1" {
let line = "{\"event\":\"sampleDuration\",\"milliseconds\":\((ProcessInfo.processInfo.systemUptime - start) * 1000)}\n"
try? FileHandle.standardOutput.write(contentsOf: Data(line.utf8))
@@ -146,11 +139,11 @@ actor SystemSampler {
volumes = value; volumeSampleTime = ProcessInfo.processInfo.systemUptime; volumeTask = nil
}
private func finishDisk(_ value: DiskHealthMetrics?) {
diskCache = value; diskDate = value == nil ? nil : Date()
diskCache = value
nextDisk = ProcessInfo.processInfo.systemUptime + (value == nil ? 600 : 3600); diskTask = nil
}
private func finishBattery(_ value: Double?) {
batteryCache = value; batteryDate = value == nil ? nil : Date()
batteryCache = value
nextBattery = ProcessInfo.processInfo.systemUptime + (value == nil ? 600 : 3600); batteryTask = nil
}
private func startProcessesIfNeeded() {