PONGo_ios/OLTListViewModel.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

43 lines
1.5 KiB
Swift

import Foundation
import Observation
@MainActor
@Observable
final class OLTListViewModel {
var phase: LoadPhase = .idle
var olts: [OLTStateDoc] = []
var search = ""
private let connection: MCMSConnection
/// Bumped per load so an overlapping/stale fetch can't commit over a newer one.
private var loadGeneration = 0
init(connection: MCMSConnection) { self.connection = connection }
var filtered: [OLTStateDoc] {
let query = search.trimmingCharacters(in: .whitespaces)
guard !query.isEmpty else { return olts }
return olts.filter {
$0.id.localizedCaseInsensitiveContains(query)
|| ($0.resolvedName?.localizedCaseInsensitiveContains(query) ?? false)
}
}
func load() async {
loadGeneration += 1
let gen = loadGeneration
phase = .loading
do {
let fetched = try await connection.olt.allStates()
let names = (try? await connection.olt.nameMap()) ?? [:]
let merged = fetched
.map { olt in var olt = olt; olt.resolvedName = names[olt.id]; return olt }
.sorted { $0.displayName.localizedCaseInsensitiveCompare($1.displayName) == .orderedAscending }
guard gen == loadGeneration, !Task.isCancelled else { return }
olts = merged
phase = .loaded
} catch {
guard gen == loadGeneration, !Task.isCancelled else { return }
phase = .failed((error as? APIError)?.localizedDescription ?? error.localizedDescription)
}
}
}