34 lines
1.9 KiB
Swift
34 lines
1.9 KiB
Swift
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)
|
|
}
|
|
}
|