perf(efficiency): 接入真实CPU能量并隔离展示与采样需求
This commit is contained in:
@@ -4,12 +4,18 @@ import Observation
|
||||
@MainActor @Observable
|
||||
final class MetricsStore {
|
||||
private(set) var snapshot = MetricsSnapshot()
|
||||
private(set) var processSnapshot: ProcessSnapshot?
|
||||
private(set) var history = MetricHistory()
|
||||
private(set) var energy: ProcessEnergySnapshot?
|
||||
private(set) var isPaused = false
|
||||
private(set) var isSystemSleeping = false
|
||||
private(set) var isDisplaySleeping = false
|
||||
private(set) var isPanelVisible = false
|
||||
let sampling: SamplingPreferences
|
||||
var effectiveMilliseconds: Int { isPanelVisible ? sampling.panelMilliseconds : sampling.backgroundMilliseconds }
|
||||
private var hasSamplingDemand: Bool { isPanelVisible || sampling.backgroundEnabled }
|
||||
private let energyEnabled: Bool
|
||||
private var panelDemand: Bool { isPanelVisible && !isDisplaySleeping }
|
||||
var effectiveMilliseconds: Int { panelDemand ? sampling.panelMilliseconds : sampling.backgroundMilliseconds }
|
||||
private var hasSamplingDemand: Bool { !isSystemSleeping && (panelDemand || sampling.backgroundEnabled) }
|
||||
@ObservationIgnored private var generation = 0
|
||||
@ObservationIgnored private var visibilityGeneration = 0
|
||||
@ObservationIgnored private var task: Task<Void, Never>?
|
||||
@@ -18,8 +24,9 @@ final class MetricsStore {
|
||||
@ObservationIgnored private var needsHistoryBoundary = true
|
||||
@ObservationIgnored private var lastPublishedAt: ContinuousClock.Instant?
|
||||
|
||||
init(sampling: SamplingPreferences? = nil, sampler: SystemSampler = SystemSampler()) {
|
||||
init(sampling: SamplingPreferences? = nil, sampler: SystemSampler = SystemSampler(), energyEnabled: Bool = true) {
|
||||
self.sampler = sampler
|
||||
self.energyEnabled = energyEnabled
|
||||
self.sampling = sampling ?? SamplingPreferences()
|
||||
self.sampling.onChange = { [weak self] in
|
||||
guard let self, !self.isPaused,
|
||||
@@ -31,6 +38,7 @@ final class MetricsStore {
|
||||
|
||||
func start() {
|
||||
guard task == nil else { return }
|
||||
if isPaused { energy = nil; visibilityGeneration += 1 }
|
||||
isPaused = false
|
||||
reschedule(reset: true)
|
||||
}
|
||||
@@ -57,21 +65,32 @@ final class MetricsStore {
|
||||
while !Task.isCancelled {
|
||||
let sampledAt = ContinuousClock.now
|
||||
let visibleGeneration = self?.visibilityGeneration
|
||||
var next = await sampler.sample(includeProcesses: self?.isPanelVisible == true,
|
||||
includeSlowMetrics: self?.isPanelVisible == true, processUpdate: { [weak self] processes in
|
||||
var next = await sampler.sample(includeProcesses: self?.panelDemand == true,
|
||||
includeSlowMetrics: self?.panelDemand == true,
|
||||
maximumEnergyInterval: max(30, Double(self?.effectiveMilliseconds ?? 2000) / 500),
|
||||
includeEnergy: self?.energyEnabled == true, demandRevision: visibleGeneration, processUpdate: { [weak self] processes in
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self, self.visibilityGeneration == visibleGeneration,
|
||||
self.isPanelVisible, !self.isPaused else { return }
|
||||
if self.snapshot.processes.map({ $0.date > processes.date }) != true { self.snapshot.processes = processes }
|
||||
self.panelDemand, !self.isPaused, !self.isSystemSleeping else { return }
|
||||
if self.processSnapshot.map({ $0.date > processes.date }) != true { self.processSnapshot = processes }
|
||||
}
|
||||
}, energyUpdate: { [weak self] energy in
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self, self.visibilityGeneration == visibleGeneration,
|
||||
self.panelDemand, !self.isPaused, !self.isSystemSleeping else { return }
|
||||
self.energy = energy
|
||||
SamplingDiagnostics.recordEnergy(energy)
|
||||
}
|
||||
})
|
||||
guard !Task.isCancelled, self?.generation == currentGeneration else { return }
|
||||
if self?.isPanelVisible != true || self?.visibilityGeneration != visibleGeneration { next.processes = nil }
|
||||
else if let completed = self?.snapshot.processes, completed.date >= next.date {
|
||||
if self?.panelDemand != true || self?.visibilityGeneration != visibleGeneration { next.processes = nil }
|
||||
else if let completed = self?.processSnapshot, completed.date >= next.date {
|
||||
// A fast detached process result may reach MainActor before this quick snapshot.
|
||||
next.processes = completed
|
||||
}
|
||||
self?.snapshot = next
|
||||
var resources = next
|
||||
resources.processes = nil
|
||||
self?.snapshot = resources
|
||||
self?.history.append(next, breakBefore: self?.needsHistoryBoundary == true, expectedInterval: Double(self?.effectiveMilliseconds ?? 5_000) / 1000)
|
||||
self?.lastPublishedAt = .now
|
||||
self?.needsHistoryBoundary = false
|
||||
@@ -92,20 +111,39 @@ final class MetricsStore {
|
||||
visibilityGeneration += 1
|
||||
task?.cancel()
|
||||
task = nil
|
||||
Task { await sampler.setProcessVisible(false) }
|
||||
let revision = visibilityGeneration
|
||||
Task { await sampler.setProcessVisible(false, revision: revision) }
|
||||
isPaused = true
|
||||
SamplingDiagnostics.record(snapshot, event: "pause")
|
||||
}
|
||||
}
|
||||
|
||||
func setSystemSleeping(_ sleeping: Bool) {
|
||||
guard sleeping != isSystemSleeping else { return }
|
||||
isSystemSleeping = sleeping
|
||||
updateDemand(reset: true)
|
||||
}
|
||||
|
||||
func setDisplaySleeping(_ sleeping: Bool) {
|
||||
guard sleeping != isDisplaySleeping else { return }
|
||||
isDisplaySleeping = sleeping
|
||||
updateDemand(reset: !sampling.backgroundEnabled, sampleImmediately: panelDemand)
|
||||
}
|
||||
|
||||
func setPanelVisible(_ visible: Bool) {
|
||||
guard isPanelVisible != visible else { return }
|
||||
visibilityGeneration += 1
|
||||
isPanelVisible = visible
|
||||
if !visible { snapshot.processes = nil }
|
||||
let active = visible && !isPaused
|
||||
Task { await sampler.setProcessVisible(active) }
|
||||
if !isPaused { reschedule(reset: !sampling.backgroundEnabled) }
|
||||
updateDemand(reset: !sampling.backgroundEnabled, sampleImmediately: panelDemand)
|
||||
}
|
||||
|
||||
private func updateDemand(reset: Bool, sampleImmediately: Bool = true) {
|
||||
visibilityGeneration += 1
|
||||
let revision = visibilityGeneration
|
||||
let active = panelDemand && !isPaused && !isSystemSleeping
|
||||
if !active { processSnapshot = nil }
|
||||
energy = nil
|
||||
Task { await sampler.setProcessVisible(active, revision: revision) }
|
||||
if !isPaused { reschedule(reset: reset, sampleImmediately: sampleImmediately) }
|
||||
}
|
||||
|
||||
deinit { task?.cancel() }
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import Foundation
|
||||
|
||||
nonisolated enum ProcessEnergyServiceClient {
|
||||
static func read(_ identities: [ProcessIdentity]) async -> ([ProcessEnergyReading], EnergyCapability) {
|
||||
var readings: [ProcessEnergyReading] = []
|
||||
var capability: EnergyCapability = .unavailable
|
||||
let deadline = ProcessInfo.processInfo.systemUptime + 3
|
||||
for start in stride(from: 0, to: identities.count, by: ProcessEnergyRequest.limit) {
|
||||
guard !Task.isCancelled, ProcessInfo.processInfo.systemUptime < deadline else { break }
|
||||
let chunk = Array(identities[start..<min(start + ProcessEnergyRequest.limit, identities.count)])
|
||||
let request = ProcessEnergyRequest(token: UUID(), identities: chunk)
|
||||
guard let data = try? JSONEncoder().encode(request), data.count <= ProcessEnergyRequest.byteLimit else { continue }
|
||||
let reply: ProcessEnergyReply? = await ServiceRequest.perform(timeout: min(1.5, deadline - ProcessInfo.processInfo.systemUptime)) { proxy, finish in
|
||||
proxy.readProcessEnergy(data) { data in
|
||||
guard let data, data.count <= 262_144,
|
||||
let value = try? JSONDecoder().decode(ProcessEnergyReply.self, from: data), value.token == request.token,
|
||||
value.readings.count == chunk.count,
|
||||
Set(value.readings.map(\.id)) == Set(chunk) else { finish(nil); return }
|
||||
finish(value)
|
||||
}
|
||||
}
|
||||
if let reply {
|
||||
if capability == .unavailable { capability = .unverified }
|
||||
if reply.capability == .unsupported { return ([], .unsupported) }
|
||||
if reply.capability == .verifiedCPU {
|
||||
capability = .verifiedCPU
|
||||
readings.append(contentsOf: reply.readings)
|
||||
}
|
||||
}
|
||||
}
|
||||
return (readings, capability)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import Foundation
|
||||
|
||||
/// Fixed read-only operation: no caller-supplied paths or commands.
|
||||
@objc protocol SMARTServiceProtocol {
|
||||
nonisolated func readProcessEnergy(_ request: Data, withReply reply: @escaping (Data?) -> Void)
|
||||
nonisolated func readSensors(cpu: Bool, gpu: Bool, fans: Bool,
|
||||
withReply reply: @escaping (NSNumber?, NSNumber?, [NSNumber]?) -> Void)
|
||||
nonisolated func readSMART(withReply reply: @escaping (NSNumber?, NSNumber?) -> Void)
|
||||
|
||||
@@ -5,7 +5,23 @@ import Darwin
|
||||
nonisolated enum SamplingDiagnostics {
|
||||
static let enabled = ProcessInfo.processInfo.environment["KYMO_DIAGNOSTICS"] == "1"
|
||||
|
||||
static func record(_ snapshot: MetricsSnapshot, event: String = "sample") {
|
||||
static func recordTextPresentation(processes: Int, cells: Int) {
|
||||
guard enabled else { return }
|
||||
let line = "{\"event\":\"textPresentation\",\"processes\":\(processes),\"createdCells\":\(cells)}\n"
|
||||
try? FileHandle.standardOutput.write(contentsOf: Data(line.utf8))
|
||||
}
|
||||
|
||||
static func recordEnergy(_ snapshot: ProcessEnergySnapshot) {
|
||||
guard enabled else { return }
|
||||
let payload: [String: Any] = ["event": "energy", "recordedAt": Date().timeIntervalSince1970,
|
||||
"state": String(describing: snapshot.state), "candidates": snapshot.candidates,
|
||||
"readable": snapshot.readable, "measured": snapshot.measured,
|
||||
"watts": snapshot.rows.map(\.watts), "intervals": snapshot.rows.map(\.seconds)]
|
||||
guard let data = try? JSONSerialization.data(withJSONObject: payload, options: [.sortedKeys]) else { return }
|
||||
try? FileHandle.standardOutput.write(contentsOf: data + Data([10]))
|
||||
}
|
||||
|
||||
static func record(_ snapshot: MetricsSnapshot, event: String = "sample", hiddenHostAlive: Bool? = nil) {
|
||||
guard enabled else { return }
|
||||
var payload: [String: Any] = [
|
||||
"event": event, "timestamp": snapshot.date.timeIntervalSince1970,
|
||||
@@ -14,6 +30,7 @@ nonisolated enum SamplingDiagnostics {
|
||||
"pid": ProcessInfo.processInfo.processIdentifier,
|
||||
"load": snapshot.load
|
||||
]
|
||||
payload["hiddenHostAlive"] = hiddenHostAlive
|
||||
payload["cpu"] = snapshot.cpu?.usage
|
||||
payload["cores"] = snapshot.cpu?.cores.count
|
||||
payload["cpuTemperature"] = snapshot.cpuTemperature
|
||||
|
||||
@@ -4,11 +4,17 @@ import Foundation
|
||||
nonisolated struct SensorSchedule {
|
||||
private(set) var deadline: TimeInterval = 0
|
||||
private var failures = 0
|
||||
private let successInterval: TimeInterval
|
||||
private let failureInterval: TimeInterval
|
||||
init(successInterval: TimeInterval = 10, failureInterval: TimeInterval = 60) {
|
||||
self.successInterval = successInterval
|
||||
self.failureInterval = failureInterval
|
||||
}
|
||||
|
||||
func isDue(at now: TimeInterval) -> Bool { now >= deadline }
|
||||
|
||||
mutating func complete(available: Bool, at now: TimeInterval) {
|
||||
failures = available ? 0 : min(failures + 1, 5)
|
||||
deadline = now + (available ? 10 : min(600, 60 * pow(2, Double(failures - 1))))
|
||||
mutating func complete(available: Bool, at now: TimeInterval, retryInterval: TimeInterval? = nil) {
|
||||
failures = available ? 0 : min(failures + 1, 8)
|
||||
deadline = now + (retryInterval ?? (available ? successInterval : min(600, failureInterval * pow(2, Double(failures - 1)))))
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user