perf(efficiency): 落实首批采样减负与发行包瘦身

This commit is contained in:
2026-11-03 23:19:52 +08:00
parent 935701fca6
commit def3b1e130
40 changed files with 483 additions and 291 deletions
+14 -3
View File
@@ -4,6 +4,7 @@ import Darwin
nonisolated struct ProcessMonitor: Sendable {
private var previous: [ProcessIdentity: (UInt64, TimeInterval)] = [:]
private var sampleSerial: UInt64 = 0
private var paths: [ProcessIdentity: (name: String, path: String?, expires: TimeInterval)] = [:]
static func cpu(current: UInt64, previous: UInt64?, elapsed: TimeInterval) -> Double? {
guard let previous, current >= previous, elapsed.isFinite, elapsed > 0 else { return nil }
@@ -15,11 +16,13 @@ nonisolated struct ProcessMonitor: Sendable {
let date = Date()
guard let entries = Self.entries() else {
previous = [:]
paths = [:]
return ProcessSnapshot(date: date, enumerated: 0, readable: 0, rows: [], failed: true)
}
let now = ProcessInfo.processInfo.systemUptime
var next: [ProcessIdentity: (UInt64, TimeInterval)] = [:]
var rows: [ProcessMetrics] = []
var pathBuffer = [CChar](repeating: 0, count: 4 * Int(MAXPATHLEN))
for entry in entries where entry.kp_proc.p_pid > 0 {
let pid = entry.kp_proc.p_pid
var info = proc_taskallinfo()
@@ -34,8 +37,14 @@ nonisolated struct ProcessMonitor: Sendable {
let name = withUnsafeBytes(of: &copy) { raw in
String(decoding: raw.prefix { $0 != 0 }, as: UTF8.self)
}
var path = [CChar](repeating: 0, count: 4 * Int(MAXPATHLEN))
let pathSize = proc_pidpath(pid, &path, UInt32(path.count))
let path: String?
if let cached = paths[id], seconds > 0, cached.name == name, now < cached.expires {
path = cached.path
} else {
let size = proc_pidpath(pid, &pathBuffer, UInt32(pathBuffer.count))
path = size > 0 ? String(cString: pathBuffer) : nil
paths[id] = (name, path, now + 30)
}
var usage: Double?
if valid && seconds > 0 {
let (total, overflow) = info.ptinfo.pti_total_user.addingReportingOverflow(info.ptinfo.pti_total_system)
@@ -44,7 +53,7 @@ nonisolated struct ProcessMonitor: Sendable {
next[id] = (total, now)
}
}
rows.append(ProcessMetrics(id: id, name: name, path: pathSize > 0 ? String(cString: path) : nil,
rows.append(ProcessMetrics(id: id, name: name, path: path,
cpu: usage, residentBytes: valid ? info.ptinfo.pti_resident_size : nil,
threads: valid ? Int(info.ptinfo.pti_threadnum) : nil, restricted: !valid))
}
@@ -56,11 +65,13 @@ nonisolated struct ProcessMonitor: Sendable {
})
rows.removeAll { $0.id.seconds > 0 && !identities.contains($0.id) }
} else {
paths = [:]
rows = rows.map { ProcessMetrics(id: $0.id, name: $0.name, path: nil, cpu: $0.cpu,
residentBytes: $0.residentBytes, threads: $0.threads, restricted: $0.restricted) }
}
let retained = Set(rows.map(\.id))
previous = next.filter { retained.contains($0.key) }
paths = paths.filter { retained.contains($0.key) && $0.key.seconds > 0 }
return ProcessSnapshot(date: date, enumerated: entries.filter { $0.kp_proc.p_pid > 0 }.count,
readable: rows.filter { !$0.restricted }.count, rows: rows, failed: false)
}
+19 -15
View File
@@ -8,7 +8,9 @@ actor SystemSampler {
private var temperatureCache: Double?
private var gpuTemperatureCache: Double?
private var fanCache: [FanMetrics]?
private var nextTemperature: TimeInterval = 0
private var cpuSchedule = SensorSchedule()
private var gpuSchedule = SensorSchedule()
private var fanSchedule = SensorSchedule()
private var didProbe = false
private let diskHealth = DiskHealthMonitor()
private let batteryHealth = SystemBatteryHealthMonitor()
@@ -50,7 +52,8 @@ actor SystemSampler {
// A synchronous OS read may outlive cancellation. Keep the in-flight slot occupied.
}
func sample(includeProcesses: Bool? = nil, processUpdate: (@Sendable (ProcessSnapshot) -> Void)? = nil) -> MetricsSnapshot {
func sample(includeProcesses: Bool? = nil, includeSlowMetrics: Bool = true,
processUpdate: (@Sendable (ProcessSnapshot) -> Void)? = nil) -> MetricsSnapshot {
guard !Task.isCancelled else { return MetricsSnapshot() }
if let includeProcesses { setProcessVisible(includeProcesses) }
self.processUpdate = processUpdate
@@ -61,12 +64,13 @@ actor SystemSampler {
let start = ProcessInfo.processInfo.systemUptime
var result = MetricsSnapshot()
result.cpu = cpu.sample()
if temperatureTask == nil && start >= nextTemperature {
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
async let cpu = CPUTemperatureServiceClient.read()
async let gpu = CPUTemperatureServiceClient.read(gpu: true)
async let fans = CPUTemperatureServiceClient.readFans()
await finishTemperature(cpu, gpu: gpu, fans: fans)
let readings = await CPUTemperatureServiceClient.readSensors(cpu: readCPU, gpu: readGPU, fans: readFans)
finishTemperature(readings, cpu: readCPU, gpu: readGPU, fans: readFans)
}
}
result.cpuTemperature = temperatureCache
@@ -82,16 +86,16 @@ actor SystemSampler {
result.batteryState = result.battery == nil ? BatteryMonitor.availability() : .present
result.gpu = GPUMonitor.sample()
result.gpuUsage = result.gpu?.usage
if volumeTask == nil && start - volumeSampleTime >= 30 {
if includeSlowMetrics && volumeTask == nil && start - volumeSampleTime >= 30 {
volumeTask = Task.detached(priority: .utility) { [self] in
let value = DiskMonitor.volumes()
await finishVolumes(value)
}
}
if diskTask == nil && start >= nextDisk {
if includeSlowMetrics && diskTask == nil && start >= nextDisk {
diskTask = Task { [self, diskHealth] in await finishDisk(diskHealth.sample()) }
}
if result.battery != nil && batteryTask == nil && start >= nextBattery {
if includeSlowMetrics && result.battery != nil && batteryTask == nil && start >= nextBattery {
batteryTask = Task { [self, batteryHealth] in await finishBattery(batteryHealth.sample()) }
}
startProcessesIfNeeded()
@@ -111,11 +115,11 @@ actor SystemSampler {
return result
}
private func finishTemperature(_ value: Double?, gpu: Double?, fans: [FanMetrics]?) {
fanCache = fans
gpuTemperatureCache = gpu
temperatureCache = value
nextTemperature = ProcessInfo.processInfo.systemUptime + (value == nil && gpu == nil && fans == nil ? 60 : 5)
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
}
@@ -1,73 +1,24 @@
import Foundation
nonisolated struct SensorReadings: Sendable {
var cpu: Double?
var gpu: Double?
var fans: [FanMetrics]?
}
nonisolated enum CPUTemperatureServiceClient {
static func read(gpu: Bool = false) async -> Double? {
let url = Bundle.main.bundleURL.appendingPathComponent("Contents/XPCServices/SMARTService.xpc")
guard let requirement = CodeIdentity.requirement(at: url) else { return nil }
return await withCheckedContinuation { continuation in
let connection = NSXPCConnection(serviceName: "cn.airnan.kymo.SMARTService")
connection.setCodeSigningRequirement(requirement)
connection.remoteObjectInterface = NSXPCInterface(with: SMARTServiceProtocol.self)
let reply = Reply(connection: connection, continuation: continuation)
connection.invalidationHandler = { reply.finish(nil) }
connection.interruptionHandler = { reply.finish(nil) }
connection.resume()
guard let proxy = connection.remoteObjectProxyWithErrorHandler({ _ in reply.finish(nil) }) as? SMARTServiceProtocol else {
reply.finish(nil)
return
static func readSensors(cpu: Bool, gpu: Bool, fans: Bool) async -> SensorReadings? {
await ServiceRequest.perform(timeout: 2) { proxy, finish in
proxy.readSensors(cpu: cpu, gpu: gpu, fans: fans) { cpu, gpu, fans in
func temperature(_ number: NSNumber?) -> Double? {
number.flatMap { $0.doubleValue.isFinite && $0.doubleValue > 0 && $0.doubleValue < 150 ? $0.doubleValue : nil }
}
let values = fans.flatMap { values -> [FanMetrics]? in
guard values.count <= 10 else { return nil }
return values.enumerated().map { FanMetrics(id: $0.offset, rpm: FanMetrics.validRPM($0.element.doubleValue)) }
}
finish(SensorReadings(cpu: temperature(cpu), gpu: temperature(gpu), fans: values))
}
let receive: (NSNumber?) -> Void = { number in
let value = number?.doubleValue
reply.finish(value.flatMap { $0.isFinite && $0 > 0 && $0 < 150 ? $0 : nil })
}
if gpu { proxy.readGPUTemperature(withReply: receive) }
else { proxy.readCPUTemperature(withReply: receive) }
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 2) { reply.finish(nil) }
}
}
static func readFans() async -> [FanMetrics]? {
let url = Bundle.main.bundleURL.appendingPathComponent("Contents/XPCServices/SMARTService.xpc")
guard let requirement = CodeIdentity.requirement(at: url) else { return nil }
return await withCheckedContinuation { continuation in
let connection = NSXPCConnection(serviceName: "cn.airnan.kymo.SMARTService")
connection.setCodeSigningRequirement(requirement)
connection.remoteObjectInterface = NSXPCInterface(with: SMARTServiceProtocol.self)
let reply = Reply(connection: connection, continuation: continuation)
connection.invalidationHandler = { reply.finish(nil) }
connection.interruptionHandler = { reply.finish(nil) }
connection.resume()
guard let proxy = connection.remoteObjectProxyWithErrorHandler({ _ in reply.finish(nil) }) as? SMARTServiceProtocol else {
reply.finish(nil); return
}
proxy.readFanSpeeds { values in
guard let values, values.count <= 10 else { reply.finish(nil); return }
reply.finish(values.enumerated().map { FanMetrics(id: $0.offset, rpm: FanMetrics.validRPM($0.element.doubleValue)) })
}
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 2) { reply.finish(nil) }
}
}
private final class Reply<Value: Sendable>: @unchecked Sendable {
private let lock = NSLock()
private var continuation: CheckedContinuation<Value?, Never>?
private let connection: NSXPCConnection
init(connection: NSXPCConnection, continuation: CheckedContinuation<Value?, Never>) {
self.connection = connection
self.continuation = continuation
}
func finish(_ value: Value?) {
lock.lock()
let callback = continuation
continuation = nil
lock.unlock()
guard let callback else { return }
connection.invalidationHandler = nil
connection.interruptionHandler = nil
connection.invalidate()
callback.resume(returning: value)
}
}
}
+12 -4
View File
@@ -9,6 +9,7 @@ final class MetricsStore {
private(set) var isPanelVisible = false
let sampling: SamplingPreferences
var effectiveMilliseconds: Int { isPanelVisible ? sampling.panelMilliseconds : sampling.backgroundMilliseconds }
private var hasSamplingDemand: Bool { isPanelVisible || sampling.backgroundEnabled }
@ObservationIgnored private var generation = 0
@ObservationIgnored private var visibilityGeneration = 0
@ObservationIgnored private var task: Task<Void, Never>?
@@ -21,7 +22,8 @@ final class MetricsStore {
self.sampler = sampler
self.sampling = sampling ?? SamplingPreferences()
self.sampling.onChange = { [weak self] in
guard let self, !self.isPaused, self.effectiveMilliseconds != self.scheduledInterval else { return }
guard let self, !self.isPaused,
self.effectiveMilliseconds != self.scheduledInterval || self.hasSamplingDemand != (self.task != nil) else { return }
self.reschedule(reset: false, sampleImmediately: false)
}
start()
@@ -36,8 +38,10 @@ final class MetricsStore {
private func reschedule(reset: Bool, sampleImmediately: Bool = true) {
generation += 1
task?.cancel()
task = nil
needsHistoryBoundary = needsHistoryBoundary || reset
scheduledInterval = effectiveMilliseconds
guard hasSamplingDemand else { needsHistoryBoundary = true; return }
var delay = Duration.zero
if !sampleImmediately, let lastPublishedAt {
delay = max(.zero, .milliseconds(effectiveMilliseconds) - lastPublishedAt.duration(to: .now))
@@ -51,8 +55,10 @@ final class MetricsStore {
}
if reset { await sampler.reset() }
while !Task.isCancelled {
let sampledAt = ContinuousClock.now
let visibleGeneration = self?.visibilityGeneration
var next = await sampler.sample(includeProcesses: self?.isPanelVisible == true, processUpdate: { [weak self] processes in
var next = await sampler.sample(includeProcesses: self?.isPanelVisible == true,
includeSlowMetrics: self?.isPanelVisible == true, processUpdate: { [weak self] processes in
Task { @MainActor [weak self] in
guard let self, self.visibilityGeneration == visibleGeneration,
self.isPanelVisible, !self.isPaused else { return }
@@ -71,7 +77,9 @@ final class MetricsStore {
self?.needsHistoryBoundary = false
SamplingDiagnostics.record(next)
let interval = self?.effectiveMilliseconds ?? 5_000
do { try await Task.sleep(for: .milliseconds(interval)) }
// Start-to-start cadence; missed deadlines do not trigger catch-up bursts.
let deadline = sampledAt.advanced(by: .milliseconds(interval))
do { try await Task.sleep(until: max(deadline, .now), clock: .continuous) }
catch { return }
}
}
@@ -97,7 +105,7 @@ final class MetricsStore {
if !visible { snapshot.processes = nil }
let active = visible && !isPaused
Task { await sampler.setProcessVisible(active) }
if !isPaused { reschedule(reset: false) }
if !isPaused { reschedule(reset: !sampling.backgroundEnabled) }
}
deinit { task?.cancel() }
+2 -39
View File
@@ -2,50 +2,13 @@ import Foundation
nonisolated enum SMARTServiceClient {
static func read() async -> DiskHealthMetrics? {
let url = Bundle.main.bundleURL.appendingPathComponent("Contents/XPCServices/SMARTService.xpc")
guard let requirement = CodeIdentity.requirement(at: url) else { return nil }
return await withCheckedContinuation { continuation in
let connection = NSXPCConnection(serviceName: "cn.airnan.kymo.SMARTService")
connection.setCodeSigningRequirement(requirement)
connection.remoteObjectInterface = NSXPCInterface(with: SMARTServiceProtocol.self)
let reply = Reply(connection: connection, continuation: continuation)
connection.invalidationHandler = { reply.finish(nil) }
connection.interruptionHandler = { reply.finish(nil) }
connection.resume()
guard let proxy = connection.remoteObjectProxyWithErrorHandler({ _ in reply.finish(nil) }) as? SMARTServiceProtocol else {
reply.finish(nil); return
}
await ServiceRequest.perform(timeout: 15) { proxy, finish in
proxy.readSMART { remaining, hours in
let life = remaining?.doubleValue
let validLife = life.flatMap { $0.isFinite && (0...1).contains($0) ? $0 : nil }
let validHours = hours.flatMap { UInt64($0.stringValue) }
reply.finish(validLife != nil || validHours != nil ? DiskHealthMetrics(remainingLife: validLife, powerOnHours: validHours) : nil)
finish(validLife != nil || validHours != nil ? DiskHealthMetrics(remainingLife: validLife, powerOnHours: validHours) : nil)
}
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 15) { reply.finish(nil) }
}
}
/// Error, interruption, timeout and reply may race; resume exactly once.
private final class Reply: @unchecked Sendable {
private let lock = NSLock()
private var continuation: CheckedContinuation<DiskHealthMetrics?, Never>?
private let connection: NSXPCConnection
init(connection: NSXPCConnection, continuation: CheckedContinuation<DiskHealthMetrics?, Never>) {
self.connection = connection
self.continuation = continuation
}
func finish(_ value: DiskHealthMetrics?) {
lock.lock()
let callback = continuation
continuation = nil
lock.unlock()
guard let callback else { return }
connection.invalidationHandler = nil
connection.interruptionHandler = nil
connection.invalidate()
callback.resume(returning: value)
}
}
}
@@ -2,8 +2,7 @@ import Foundation
/// Fixed read-only operation: no caller-supplied paths or commands.
@objc protocol SMARTServiceProtocol {
nonisolated func readFanSpeeds(withReply reply: @escaping ([NSNumber]?) -> 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)
nonisolated func readGPUTemperature(withReply reply: @escaping (NSNumber?) -> Void)
nonisolated func readCPUTemperature(withReply reply: @escaping (NSNumber?) -> Void)
}
@@ -9,6 +9,8 @@ nonisolated enum SamplingDiagnostics {
guard enabled else { return }
var payload: [String: Any] = [
"event": event, "timestamp": snapshot.date.timeIntervalSince1970,
"recordedAt": Date().timeIntervalSince1970,
"uptime": ProcessInfo.processInfo.systemUptime,
"pid": ProcessInfo.processInfo.processIdentifier,
"load": snapshot.load
]
@@ -44,6 +46,7 @@ nonisolated enum SamplingDiagnostics {
if status == KERN_SUCCESS {
payload["residentBytes"] = info.resident_size
payload["footprintBytes"] = info.phys_footprint
payload["peakFootprintBytes"] = info.ledger_phys_footprint_peak
}
guard let data = try? JSONSerialization.data(withJSONObject: payload, options: [.sortedKeys]) else { return }
try? FileHandle.standardOutput.write(contentsOf: data + Data([10]))
+21 -1
View File
@@ -10,6 +10,16 @@ import CoreFoundation
@ObservationIgnored var onChange: (() -> Void)?
private var panelValue: Int
private var backgroundValue: Int
private var backgroundEnabledValue: Bool
var backgroundEnabled: Bool {
get { backgroundEnabledValue }
set {
guard newValue != backgroundEnabledValue else { return }
backgroundEnabledValue = newValue
defaults.set(newValue, forKey: "sampling.backgroundEnabled")
onChange?()
}
}
var panelMilliseconds: Int {
get { panelValue }
set {
@@ -34,7 +44,17 @@ import CoreFoundation
init(defaults: UserDefaults = .standard) {
self.defaults = defaults
panelValue = Self.read(defaults, key: "sampling.panelMilliseconds", fallback: 2_000)
backgroundValue = Self.read(defaults, key: "sampling.backgroundMilliseconds", fallback: 5_000)
backgroundValue = Self.read(defaults, key: "sampling.backgroundMilliseconds", fallback: 30_000)
// Retain an existing explicit background interval; new installs have no hidden consumer.
if let number = defaults.object(forKey: "sampling.backgroundEnabled") as? NSNumber,
CFGetTypeID(number) == CFBooleanGetTypeID() {
backgroundEnabledValue = number.boolValue
} else if let number = defaults.object(forKey: "sampling.backgroundMilliseconds") as? NSNumber,
CFGetTypeID(number) != CFBooleanGetTypeID(), number.doubleValue.isFinite {
backgroundEnabledValue = true
} else {
backgroundEnabledValue = false
}
}
static func normalized(_ value: Int) -> Int {
+14
View File
@@ -0,0 +1,14 @@
import Foundation
/// Missing capabilities back off independently; success in another zone cannot reset this state.
nonisolated struct SensorSchedule {
private(set) var deadline: TimeInterval = 0
private var failures = 0
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))))
}
}
+68
View File
@@ -0,0 +1,68 @@
import Foundation
/// One short-lived authenticated connection. Every completion releases the timer and connection.
nonisolated enum ServiceRequest {
private static let requirement = CodeIdentity.requirement(at:
Bundle.main.bundleURL.appendingPathComponent("Contents/XPCServices/SMARTService.xpc"))
static func perform<Value: Sendable>(timeout: TimeInterval,
invoke: @escaping (SMARTServiceProtocol, @escaping @Sendable (Value?) -> Void) -> Void
) async -> Value? {
guard let requirement else { return nil }
let request = Pending<Value>()
return await withTaskCancellationHandler {
await withCheckedContinuation { continuation in
request.start(requirement: requirement, timeout: timeout, continuation: continuation, invoke: invoke)
}
} onCancel: { request.finish(nil) }
}
private final class Pending<Value: Sendable>: @unchecked Sendable {
private let lock = NSLock()
private var finished = false
private var continuation: CheckedContinuation<Value?, Never>?
private var connection: NSXPCConnection?
private var timer: DispatchSourceTimer?
func start(requirement: String, timeout: TimeInterval, continuation: CheckedContinuation<Value?, Never>,
invoke: (SMARTServiceProtocol, @escaping @Sendable (Value?) -> Void) -> Void) {
lock.lock()
guard !finished else { lock.unlock(); continuation.resume(returning: nil); return }
self.continuation = continuation
let connection = NSXPCConnection(serviceName: "cn.airnan.kymo.SMARTService")
self.connection = connection
connection.setCodeSigningRequirement(requirement)
connection.remoteObjectInterface = NSXPCInterface(with: SMARTServiceProtocol.self)
connection.invalidationHandler = { [weak self] in self?.finish(nil) }
connection.interruptionHandler = { [weak self] in self?.finish(nil) }
let timer = DispatchSource.makeTimerSource(queue: .global(qos: .utility))
self.timer = timer
timer.schedule(deadline: .now() + timeout)
timer.setEventHandler { [weak self] in self?.finish(nil) }
timer.resume()
connection.resume()
lock.unlock()
guard let proxy = connection.remoteObjectProxyWithErrorHandler({ [weak self] _ in self?.finish(nil) }) as? SMARTServiceProtocol else {
finish(nil); return
}
invoke(proxy) { [weak self] in self?.finish($0) }
}
func finish(_ value: Value?) {
lock.lock()
guard !finished else { lock.unlock(); return }
finished = true
let callback = continuation
let timer = timer
let connection = connection
continuation = nil; self.timer = nil; self.connection = nil
lock.unlock()
timer?.setEventHandler {}
timer?.cancel()
connection?.invalidationHandler = nil
connection?.interruptionHandler = nil
connection?.invalidate()
callback?.resume(returning: value)
}
}
}