PONGo_ios/ONURepository.swift
Jon Vanvik 203465913c Apply code-review fixes: identity/pagination, load races, TLS pin, leaks
Addresses a multi-agent code review (26 confirmed findings + a URLSession
leak) across correctness, concurrency, security, and cleanup:

- MongoDocument.id: deterministic fallback (was UUID() on every access) to stop
  SwiftUI List/ForEach identity churn; getAll pagination drives its cursor off
  the real _id via documentId, so a missing _id stops paging instead of looping
  on a fabricated cursor.
- View models: per-load generation guard (+ captured-tab guard on ONU detail)
  so a cancelled or overlapping load can't commit stale results or land data on
  the wrong tab.
- JSONValue.intValue: guard Int(d) against NaN/inf/out-of-range (crash).
- ServerTrustEvaluator: hash the real SubjectPublicKeyInfo (prepend the
  algorithm-specific ASN.1 SPKI header) so a standard openssl-captured
  public-key pin actually matches; unknown key types fail closed.
- AppEnvironment.configure: clear stale cookies + Keychain creds on host change.
- FirmwareFile.isCompatible: empty metadata no longer passes as compatible-for-all.
- APIClient: invalidate URLSession on deinit (per-configure/probe leak).
- Dashboard best-effort sections keep last-good on transient failure; unified
  optical thresholds; LoginView prefill-once; populatedBuckets unique ForEach id;
  Format rounding rollover; dead-code/docstring/dedup cleanups.

Verification pending on the Mac (no Swift toolchain on the Linux dev box).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-31 16:36:49 +02:00

118 lines
4.7 KiB
Swift

import Foundation
/// ONU resources and operations.
@MainActor
final class ONURepository {
private let client: APIClient
init(client: APIClient) { self.client = client }
// MARK: Lists
func states(query: APIQuery = .empty) async throws -> [ONUStateDoc] {
try await client.get(.onuStates, query: query, as: [ONUStateDoc].self)
}
/// Fetch every ONU state, paging through with the `next` cursor.
func allStates() async throws -> [ONUStateDoc] {
try await client.getAll(.onuStates, idOf: { $0.documentId })
}
func configs(query: APIQuery = .empty) async throws -> [ONUConfigDoc] {
try await client.get(.onuConfigs, query: query, as: [ONUConfigDoc].self)
}
/// Map of ONU id operator name. Uses a `projection` so only `ONU.Name`
/// comes back full ONU-CFG docs are ~30 KB each, the name is a few bytes.
func nameMap() async throws -> [String: String] {
var query = APIQuery()
query.projection = ["ONU.Name": 1]
let configs: [ONUConfigDoc] = try await client.getAll(.onuConfigs, baseQuery: query, idOf: { $0.documentId })
return configs.reduce(into: [:]) { map, config in
if let name = config.name, !name.isEmpty { map[config.id] = name }
}
}
// MARK: Detail
func state(id: String) async throws -> ONUStateDoc {
try await client.get(.onuState(id: id), as: ONUStateDoc.self)
}
func config(id: String) async throws -> ONUConfigDoc {
try await client.get(.onuConfig(id: id), as: ONUConfigDoc.self)
}
func stats(id: String, lastHours: Int = 24) async throws -> [StatSample] {
try await client.get(.onuStats(id: id),
query: .window(lastHours: lastHours),
as: [StatSample].self)
}
func logs(id: String, lastHours: Int = 24) async throws -> [LogEntry] {
try await client.get(.onuLogs(id: id),
query: .window(lastHours: lastHours),
as: [LogEntry].self)
}
func alarmHistory(id: String) async throws -> AlarmHistoryDoc {
try await client.get(.onuAlarmHistory(id: id), as: AlarmHistoryDoc.self)
}
func alarmHistories(query: APIQuery = .empty) async throws -> [AlarmHistoryDoc] {
try await client.get(.onuAlarmHistories, query: query, as: [AlarmHistoryDoc].self)
}
func cpeStates(query: APIQuery = .empty) async throws -> [CPEState] {
try await client.get(.onuCPEStates, query: query, as: [CPEState].self)
}
/// Per-CPE DHCP/lease state from the web helper `/cpe/onu/<id>/`, which
/// returns a bare `[code, cpe, ]` array. Returns the CPE objects.
func cpes(id: String) async throws -> [CPEState] {
let raw = try await client.getRaw(.onuCPE(id: id))
guard let array = raw.arrayValue else { return [] }
return array.compactMap { $0.objectValue != nil ? CPEState(raw: $0) : nil }
}
// MARK: Firmware
func firmwareFiles() async throws -> [FirmwareFile] {
try await client.get(.onuFirmwareFiles, as: [FirmwareFile].self)
}
/// Procedure 7: stage `file` in the ONU's inactive firmware bank via a
/// full-document PUT. Returns the bank slot written. Service-affecting
/// gate behind an explicit confirmation.
@discardableResult
func upgradeFirmware(id: String, file: FirmwareFile) async throws -> Int {
guard let filename = file.filename, let version = file.version else {
throw APIError.encoding(message: "Firmware file is missing a filename or version.")
}
let config = try await config(id: id)
guard let result = FirmwareUpgrade.apply(to: config.raw, filename: filename, version: version) else {
throw APIError.encoding(message: "Unexpected ONU-CFG shape — firmware write aborted.")
}
try await putConfig(id: id, document: result.document)
return result.slot
}
// MARK: Operations (consequential gate behind confirm dialogs)
/// `PUT /onus/<id>/reset/`
func reset(id: String) async throws {
let _: JSONValue = try await client.action("PUT", .onuReset(id: id), as: JSONValue.self)
}
/// `DELETE /onus/configs/<id>/`
func delete(id: String) async throws {
try await client.delete(.onuConfig(id: id))
}
/// GET-modify-PUT: upload a full replacement ONU-CFG document.
/// Mutate the `raw` JSONValue from `config(id:)`, then pass it here.
func putConfig(id: String, document: JSONValue) async throws {
let _: JSONValue = try await client.send(
"PUT", .onuConfig(id: id),
body: document, wrapInData: true, as: JSONValue.self)
}
}