import Foundation import Darwin /// One coordinator owns baselines; slow workers have at most one in-flight call each. actor SystemSampler { private var cpu = CPUMonitor() private var temperatureTask: Task? private var temperatureCache: Double? private var gpuTemperatureCache: Double? private var fanCache: [FanMetrics]? private var cpuSchedule = SensorSchedule() private var gpuSchedule = SensorSchedule() private var fanSchedule = SensorSchedule() private var didProbe = false private let diskHealth = DiskHealthMonitor() private let batteryHealth = SystemBatteryHealthMonitor() private var network = NetworkMonitor() private let networkPath = NetworkPathObserver() private var diskIO = DiskIOMonitor() private var volumes: [VolumeMetrics]? private var volumeSampleTime: TimeInterval = -.infinity private var volumeTask: Task? private var diskTask: Task? private var batteryTask: Task? 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 private var processMonitor = ProcessMonitor() private var energyMonitor = ProcessEnergyMonitor() private var energyTask: Task? private var energySchedule = SensorSchedule(successInterval: 5, failureInterval: 30) private var maximumEnergyInterval: TimeInterval = 30 private var energyUpdate: (@Sendable (ProcessEnergySnapshot) -> Void)? private var processTask: Task? private var processCache: ProcessSnapshot? private var processUpdate: (@Sendable (ProcessSnapshot) -> Void)? private var processVisible = false private var processGeneration = 0 private var demandRevision = Int.min init(processRead: @escaping @Sendable (inout ProcessMonitor) -> ProcessSnapshot = { $0.sample() }) { self.processRead = processRead } func reset() { cpu = CPUMonitor(); network = NetworkMonitor(); diskIO = DiskIOMonitor() } func setProcessVisible(_ visible: Bool, revision: Int? = nil) { var changedRevision = false if let revision { guard revision >= demandRevision else { return } changedRevision = revision != demandRevision demandRevision = revision } guard visible != processVisible || changedRevision else { return } processVisible = visible processGeneration += 1 processCache = nil if !visible { processUpdate = nil; energyUpdate = nil } energyTask?.cancel() energyMonitor = ProcessEnergyMonitor() energySchedule = SensorSchedule(successInterval: 5, failureInterval: 30) processMonitor = ProcessMonitor() // 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, processUpdate: (@Sendable (ProcessSnapshot) -> Void)? = nil, energyUpdate: (@Sendable (ProcessEnergySnapshot) -> Void)? = nil) -> MetricsSnapshot { guard !Task.isCancelled else { return MetricsSnapshot() } if let demandRevision, demandRevision < self.demandRevision { return MetricsSnapshot() } setProcessVisible(includeProcesses ?? processVisible, revision: demandRevision) self.maximumEnergyInterval = min(3600, max(30, maximumEnergyInterval)) self.processUpdate = processUpdate self.energyUpdate = includeEnergy ? energyUpdate : nil if !didProbe { didProbe = true if ProcessInfo.processInfo.environment["KYMO_PANEL_PROBE"] == "1" { PanelCapabilityProbe.run() } } let start = ProcessInfo.processInfo.systemUptime var result = MetricsSnapshot() result.cpu = cpu.sample() let readCPU = cpuSchedule.isDue(at: start) let readGPU = gpuSchedule.isDue(at: start) let readFans = fanSchedule.isDue(at: start) if includeSlowMetrics && temperatureTask == nil && (readCPU || readGPU || readFans) { temperatureTask = Task { [self] in let readings = await CPUTemperatureServiceClient.readSensors(cpu: readCPU, gpu: readGPU, fans: readFans) finishTemperature(readings, cpu: readCPU, gpu: readGPU, fans: readFans) } } result.cpuTemperature = temperatureCache result.gpuTemperature = gpuTemperatureCache result.fans = fanCache result.memory = MemoryMonitor.sample() result.network = network.sample() result.networkPath = networkPath.snapshot() result.defaultNetworkInterface = networkPath.defaultInterface() result.disk = DiskMonitor.sample() result.diskIO = diskIO.sample() 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() await finishVolumes(value) } } if includeSlowMetrics && diskTask == nil && start >= nextDisk { diskTask = Task { [self, diskHealth] in await finishDisk(diskHealth.sample()) } } if includeSlowMetrics && result.battery != nil && batteryTask == nil && start >= nextBattery { batteryTask = Task { [self, batteryHealth] in await finishBattery(batteryHealth.sample()) } } 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)) } return result } private func finishTemperature(_ readings: SensorReadings?, cpu: Bool, gpu: Bool, fans: Bool) { let now = ProcessInfo.processInfo.systemUptime if cpu { temperatureCache = readings?.cpu; cpuSchedule.complete(available: temperatureCache != nil, at: now) } if gpu { gpuTemperatureCache = readings?.gpu; gpuSchedule.complete(available: gpuTemperatureCache != nil, at: now) } if fans { fanCache = readings?.fans; fanSchedule.complete(available: fanCache != nil, at: now) } temperatureTask = nil } private func finishVolumes(_ value: [VolumeMetrics]?) { volumes = value; volumeSampleTime = ProcessInfo.processInfo.systemUptime; volumeTask = nil } private func finishDisk(_ value: DiskHealthMetrics?) { diskCache = value; diskDate = value == nil ? nil : Date() nextDisk = ProcessInfo.processInfo.systemUptime + (value == nil ? 600 : 3600); diskTask = nil } private func finishBattery(_ value: Double?) { batteryCache = value; batteryDate = value == nil ? nil : Date() nextBattery = ProcessInfo.processInfo.systemUptime + (value == nil ? 600 : 3600); batteryTask = nil } private func startProcessesIfNeeded() { guard processVisible, processTask == nil else { return } let generation = processGeneration let monitor = processMonitor let read = processRead processTask = Task.detached(priority: .utility) { [self] in var worker = monitor let value = read(&worker) let memory = await ProcessMemoryServiceClient.read(value.rows.map(\.id)) await finishProcesses(value.withMemory(memory), monitor: worker, generation: generation) } } private func finishProcesses(_ value: ProcessSnapshot, monitor: ProcessMonitor, generation: Int) { processTask = nil guard processVisible else { return } guard generation == processGeneration else { // Reopening requested a new generation while the old synchronous read held its slot. // Fulfil that deferred request now, without waiting for another polling interval. startProcessesIfNeeded() return } processMonitor = monitor; processCache = value processUpdate?(value) startEnergyIfNeeded(value) } private func startEnergyIfNeeded(_ processes: ProcessSnapshot) { guard processVisible, energyUpdate != nil, energyTask == nil, energySchedule.isDue(at: ProcessInfo.processInfo.systemUptime) else { return } let generation = processGeneration energyTask = Task { [self] in let (readings, capability) = await ProcessEnergyServiceClient.read(processes.rows.map(\.id)) finishEnergy(processes, readings: readings, capability: capability, generation: generation) } } private func finishEnergy(_ processes: ProcessSnapshot, readings: [ProcessEnergyReading], capability: EnergyCapability, generation: Int) { energyTask = nil guard processVisible, processGeneration == generation else { return } energySchedule.complete(available: capability == .verifiedCPU, at: ProcessInfo.processInfo.systemUptime, retryInterval: capability == .unsupported ? 600 : nil) energyUpdate?(energyMonitor.update(processes: processes, readings: readings, capability: capability, maximumInterval: maximumEnergyInterval)) } }