39 lines
1.5 KiB
Swift
39 lines
1.5 KiB
Swift
import Foundation
|
|
import Darwin
|
|
|
|
/// Serial ownership keeps CPU baselines coherent and system calls off MainActor.
|
|
actor SystemSampler {
|
|
private var cpu = CPUMonitor()
|
|
private let batteryHealth = SystemBatteryHealthMonitor()
|
|
|
|
private var network = NetworkMonitor()
|
|
private let networkPath = NetworkPathObserver()
|
|
private var diskIO = DiskIOMonitor()
|
|
private var volumes: [VolumeMetrics]?
|
|
private var volumeSampleTime: TimeInterval?
|
|
|
|
func reset() { cpu = CPUMonitor(); network = NetworkMonitor(); diskIO = DiskIOMonitor() }
|
|
|
|
func sample() async -> MetricsSnapshot {
|
|
var result = MetricsSnapshot()
|
|
result.cpu = cpu.sample()
|
|
result.memory = MemoryMonitor.sample()
|
|
result.network = network.sample()
|
|
result.networkPath = networkPath.snapshot()
|
|
result.disk = DiskMonitor.sample()
|
|
result.diskIO = diskIO.sample()
|
|
let now = ProcessInfo.processInfo.systemUptime
|
|
if volumeSampleTime == nil || now - (volumeSampleTime ?? 0) >= 30 {
|
|
volumes = DiskMonitor.volumes()
|
|
volumeSampleTime = now
|
|
}
|
|
result.volumes = volumes
|
|
result.battery = BatteryMonitor.sample()
|
|
if result.battery != nil { result.battery?.health = await batteryHealth.sample() }
|
|
result.uptime = ProcessInfo.processInfo.systemUptime
|
|
var load = [Double](repeating: 0, count: 3)
|
|
if getloadavg(&load, 3) == 3 { result.load = load }
|
|
return result
|
|
}
|
|
}
|