perf(efficiency): 落实首批采样减负与发行包瘦身
This commit is contained in:
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,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]))
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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))))
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user