Files
Kymo/kymo/Core/Models/ProcessMetrics.swift
T

72 lines
2.4 KiB
Swift

import Foundation
nonisolated struct ProcessIdentity: Hashable, Codable, Sendable {
let pid: Int32
let seconds: UInt64
let microseconds: UInt64
}
nonisolated struct ProcessMetrics: Identifiable, Sendable {
let id: ProcessIdentity
let name: String
let path: String?
let cpu: Double? // One logical CPU = 100%; may exceed 1.
let footprintBytes: UInt64? // Physical footprint; never RSS.
let threads: Int?
let restricted: Bool
var cpuPower: Double? = nil // Average attributed CPU power, watts; not Energy Impact.
var powerWindow: TimeInterval? = nil
var formattedPower: String {
guard let cpuPower, cpuPower.isFinite, cpuPower >= 0 else { return "--" }
return cpuPower >= 1 ? String(format: "%.2f W", cpuPower) : String(format: "%.1f mW", cpuPower * 1000)
}
}
nonisolated struct ProcessSnapshot: Sendable {
let date: Date
let enumerated: Int
let readable: Int
let rows: [ProcessMetrics]
let failed: Bool
}
nonisolated extension ProcessSnapshot {
func highestCPUProcesses(limit: Int) -> [ProcessMetrics] {
guard limit > 0 else { return [] }
var result: [ProcessMetrics] = []
for row in rows {
guard let cpu = row.cpu, cpu.isFinite, cpu >= 0 else { continue }
let index = result.firstIndex { ($0.cpu ?? 0) < cpu } ?? result.endIndex
result.insert(row, at: index)
if result.count > limit { result.removeLast() }
}
return result
}
var highestCPUProcess: ProcessMetrics? {
highestCPUProcesses(limit: 1).first
}
}
nonisolated struct ProcessMemoryRequest: Codable, Sendable {
let token: UUID
let identities: [ProcessIdentity]
static let limit = 256
static let byteLimit = 65_536
}
nonisolated struct ProcessMemoryReading: Codable, Sendable {
let id: ProcessIdentity
let footprintBytes: UInt64?
}
nonisolated struct ProcessMemoryReply: Codable, Sendable {
let token: UUID
let readings: [ProcessMemoryReading]
}
nonisolated extension ProcessSnapshot {
func withMemory(_ values: [ProcessIdentity: UInt64]) -> ProcessSnapshot {
ProcessSnapshot(date: date, enumerated: enumerated, readable: readable,
rows: rows.map { ProcessMetrics(id: $0.id, name: $0.name, path: $0.path, cpu: $0.cpu,
footprintBytes: values[$0.id], threads: $0.threads, restricted: $0.restricted) }, failed: failed)
}
}