feat(storage): 新增只读 SMART 辅助服务与寿命通电详情

This commit is contained in:
2026-10-30 16:02:46 +08:00
parent 069e2e100f
commit 7e9728899d
25 changed files with 515 additions and 15 deletions
+7
View File
@@ -0,0 +1,7 @@
import Foundation
nonisolated struct DiskHealthMetrics: Sendable {
/// NVMe vendor endurance estimate, not a probability of remaining failure-free.
let remainingLife: Double?
let powerOnHours: UInt64?
}
+1
View File
@@ -24,6 +24,7 @@ nonisolated struct MetricsSnapshot: Sendable {
var network: [NetworkInterfaceMetrics]?
var networkPath: NetworkPathStatus?
var disk: DiskMetrics?
var diskHealth: DiskHealthMetrics?
var diskIO: DiskIOMetrics?
var volumes: [VolumeMetrics]?
var battery: BatteryMetrics?
@@ -0,0 +1,19 @@
import Foundation
/// SMART belongs to the physical storage backing the home volume, not each APFS volume.
actor DiskHealthMonitor {
private var cached: DiskHealthMetrics?
private var nextRead: TimeInterval = 0
private var pending: Task<DiskHealthMetrics?, Never>?
func sample() async -> DiskHealthMetrics? {
if let pending { return await pending.value }
guard ProcessInfo.processInfo.systemUptime >= nextRead else { return cached }
let task = Task { await SMARTServiceClient.read() }
pending = task
cached = await task.value
pending = nil
nextRead = ProcessInfo.processInfo.systemUptime + (cached == nil ? 600 : 3600)
return cached
}
}
+20
View File
@@ -0,0 +1,20 @@
import Foundation
nonisolated enum DiskHealthReport {
static func parse(_ data: Data) -> DiskHealthMetrics? {
guard let root = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any],
let smart = root["SMARTDeviceSpecificKeysMayVaryNotGuaranteed"] as? [String: Any] else { return nil }
// Multiple physical stores cannot be represented as one device's lifetime.
if let stores = root["APFSPhysicalStores"] as? [Any], stores.count != 1 { return nil }
func integer(_ key: String) -> UInt64? {
guard let value = smart[key] as? NSNumber,
CFGetTypeID(value) != CFBooleanGetTypeID() else { return nil }
return UInt64(value.stringValue)
}
let used = integer("PERCENTAGE_USED").flatMap { $0 <= 255 ? $0 : nil }
let remaining = used.map { Double(100 - min(100, $0)) / 100 }
let hours = integer("POWER_ON_HOURS_1") == 0 ? integer("POWER_ON_HOURS_0") : nil
guard remaining != nil || hours != nil else { return nil }
return DiskHealthMetrics(remainingLife: remaining, powerOnHours: hours)
}
}
+2
View File
@@ -4,6 +4,7 @@ import Darwin
/// Serial ownership keeps CPU baselines coherent and system calls off MainActor.
actor SystemSampler {
private var cpu = CPUMonitor()
private let diskHealth = DiskHealthMonitor()
private let batteryHealth = SystemBatteryHealthMonitor()
private var network = NetworkMonitor()
@@ -21,6 +22,7 @@ actor SystemSampler {
result.network = network.sample()
result.networkPath = networkPath.snapshot()
result.disk = DiskMonitor.sample()
result.diskHealth = await diskHealth.sample()
result.diskIO = diskIO.sample()
let now = ProcessInfo.processInfo.systemUptime
if volumeSampleTime == nil || now - (volumeSampleTime ?? 0) >= 30 {
+16
View File
@@ -0,0 +1,16 @@
import Foundation
import Security
nonisolated enum CodeIdentity {
static func requirement(at url: URL) -> String? {
var code: SecStaticCode?
guard SecStaticCodeCreateWithPath(url as CFURL, [], &code) == errSecSuccess,
let code else { return nil }
var requirement: SecRequirement?
guard SecCodeCopyDesignatedRequirement(code, [], &requirement) == errSecSuccess,
let requirement else { return nil }
var text: CFString?
guard SecRequirementCopyString(requirement, [], &text) == errSecSuccess else { return nil }
return text as String?
}
}
@@ -0,0 +1,51 @@
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
}
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)
}
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)
}
}
}
@@ -0,0 +1,6 @@
import Foundation
/// Fixed read-only operation: no caller-supplied paths or commands.
@objc protocol SMARTServiceProtocol {
nonisolated func readSMART(withReply reply: @escaping (NSNumber?, NSNumber?) -> Void)
}
@@ -21,6 +21,8 @@ nonisolated enum SamplingDiagnostics {
payload["networkPath"] = snapshot.networkPath.map { String(describing: $0) }
payload["networkDownload"] = snapshot.downloadRate
payload["networkInterfaces"] = snapshot.network?.map(\.name)
payload["diskRemainingLife"] = snapshot.diskHealth?.remainingLife
payload["diskPowerOnHours"] = snapshot.diskHealth?.powerOnHours
payload["diskRead"] = snapshot.diskIO?.read
payload["diskWrite"] = snapshot.diskIO?.written
payload["volumeCount"] = snapshot.volumes?.count