Commit 31f090e160

31f090e16016adbcbc52a3b02017be21557d810f

parent: 50415157d2

Unsigned

cmc <hello@cleberg.net> · 2026-10-25 07:14 UTC

Build the dashboard once per render (!34)

You asked me to extract batch and portfolio as owning types to get the ratchet
below 200. I measured first, and that isn't reachable by moving code — but there
was a *high* severity finding sitting in exactly this file, so that's what I
did. Numbers below.

## A4, and it was worse than the finding said

`portfolioDashboardStamp()` built a signature of every tracked domain, the last
250 history rows and the last 100 monitoring logs with
`.formatted(.number.precision(.fractionLength(3)))` — roughly 350
interpolations — then compared arrays, on **every** access to
`portfolioDashboardData`.

The finding says `DashboardView.body` reads it six times plus twice per
`filteredPortfolio*`. In fact each of those five properties re-read the data
*and* re-derived the visible set through `filteredPortfolioDomainStates`, and
the view reads each twice — so the dashboard was rebuilt **more than twenty
times per render**, each rebuild paying those 350 interpolations.

The stamp and both caches are deleted. Filtering is a function of the data now,
`PortfolioDashboardData.filtered(by:searchText:)`, so the view reads once,
filters once, and passes the result down.

`matchesPortfolioFilter`, `matchesDashboardSearch`, `buildPortfolioGroups` and
`healthRank` moved onto the types they describe — `healthRank` becomes
`DomainHealth.severityRank`, which is where a property of a health value
belongs.

## 15 tests, where there were none

Every filter including the 24-hour `changed` window, search matching domain and
apex case-insensitively, trimming, filter-and-search combining, the dependent
lists staying consistent with the visible set, the summary counts deliberately
*not* following the filter (they're what the filter is chosen from), and group
ordering within and between groups.

One of them failed first time and it was my expectation that was wrong, not the
code: `"  a.  "` trims to `"a."`, which `a.example` does contain. Fixed the
assertion to pin the real behaviour.

## Why 200 isn't reachable this way

| step | complexity |
|---|---|
| before | 280 |
| A4 (caches and stamp out, 125 lines) | 279 |
| portfolio value types to their own file (145 lines) | 272 |

The last 145 lines out bought 8 points. What remains is orchestration, not
separable clusters. Ratchet goes to 280.

The batch pipeline writes six `private(set)` properties and calls back into
eight view-model members (`saveHistoryEntry`, `previousSnapshot`,
`trackedDomain`, `historyEntry`, `notifySweepComplete`, `workflowInsights`, and
both bulk-persistence toggles). Extracting it either widens that state to
module-internal or carries a back-reference into the view model — preserving the
coupling while adding indirection, for a lint number. That's restructuring the
lookup pipeline, not relocating it, and it deserves to be its own decision
rather than a side effect of a threshold.

## Verification

257 tests, 0 failures on iOS 18.6 (iPhone 16) and iOS 27.0 (iPhone Air), plus
the accessibility audit on the floor runtime since `DashboardView` changed.

Layout: unified · split

.qlty/qlty.toml +12 −12
@@ -44,18 +44,18 @@ enabled = false
4444# above today's worst file and fails anything past it. Lower it when a file is
4545# genuinely split, never raise it to make a commit pass.
4646#
47# Measured after moving DomainViewModel's export formatters out:
48# DomainViewModel 280, CloudSyncService 198, WatchlistView 146,
49# DomainDataPortabilityService 146, AuditViews 128, ContentView 119,
50# DomainDiffViews 115, DomainReportExporter 114, SettingsViews 112,
51# WorkflowsView 107.
47# Measured after A4 and the portfolio split: DomainViewModel 272,
48# CloudSyncService 198, WatchlistView 146, DomainDataPortabilityService 146,
49# AuditViews 128, ContentView 119, DomainDiffViews 115,
50# DomainReportExporter 114, SettingsViews 112, WorkflowsView 107.
5251#
53# DomainViewModel still holds this threshold where it is. Getting below about
54# 200 needs batch and portfolio out of it, and neither is a file move: Swift
55# extensions cannot hold stored properties, so the batch pipeline's six
56# `private(set)` properties and the portfolio caches would have to become
57# settable from any file. That trades real encapsulation for a lint number.
58# Extracting them as types that own their state is the way; see A13.
52# DomainViewModel still holds this threshold, and moving code has stopped
53# paying: the last 145 lines out of it bought 8 points, because what is left
54# is orchestration rather than separable clusters. Going much below 270 needs
55# the batch pipeline restructured, not relocated — it writes six
56# `private(set)` properties and calls back into eight view-model members, so
57# any extraction either widens that state or carries a back-reference. See
58# A13 for the measurements.
5959[smells.file_complexity]
6060enabled = true
6161
@@ -84,4 +84,4 @@ filter_patterns = [
8484]
8585
8686[language.swift.smells.file_complexity]
87threshold = 290
87threshold = 280
DomainDig.xcodeproj/project.pbxproj +4
@@ -35,6 +35,7 @@
3535 A1B2C3D40000000000001102 /* LookupCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001101 /* LookupCacheTests.swift */; };
3636 A1B2C3D40000000000001202 /* HistoryStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001201 /* HistoryStoreTests.swift */; };
3737 A1B2C3D40000000000001402 /* SectionStateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001401 /* SectionStateTests.swift */; };
38 A1B2C3D40000000000001502 /* PortfolioDashboardTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001501 /* PortfolioDashboardTests.swift */; };
3839 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000301 /* AvailabilityTests.swift */; };
3940 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */; };
4041 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000501 /* DomainNameTests.swift */; };
@@ -117,6 +118,7 @@
117118 A1B2C3D40000000000001101 /* LookupCacheTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = LookupCacheTests.swift; sourceTree = "<group>"; };
118119 A1B2C3D40000000000001201 /* HistoryStoreTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HistoryStoreTests.swift; sourceTree = "<group>"; };
119120 A1B2C3D40000000000001401 /* SectionStateTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SectionStateTests.swift; sourceTree = "<group>"; };
121 A1B2C3D40000000000001501 /* PortfolioDashboardTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PortfolioDashboardTests.swift; sourceTree = "<group>"; };
120122 A1B2C3D40000000000000301 /* AvailabilityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AvailabilityTests.swift; sourceTree = "<group>"; };
121123 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudSyncMergeTests.swift; sourceTree = "<group>"; };
122124 A1B2C3D40000000000000501 /* DomainNameTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainNameTests.swift; sourceTree = "<group>"; };
@@ -264,6 +266,7 @@
264266 A1B2C3D40000000000001101 /* LookupCacheTests.swift */,
265267 A1B2C3D40000000000001201 /* HistoryStoreTests.swift */,
266268 A1B2C3D40000000000001401 /* SectionStateTests.swift */,
269 A1B2C3D40000000000001501 /* PortfolioDashboardTests.swift */,
267270 A1B2C3D40000000000000301 /* AvailabilityTests.swift */,
268271 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */,
269272 A1B2C3D40000000000000501 /* DomainNameTests.swift */,
@@ -536,6 +539,7 @@
536539 A1B2C3D40000000000001102 /* LookupCacheTests.swift in Sources */,
537540 A1B2C3D40000000000001202 /* HistoryStoreTests.swift in Sources */,
538541 A1B2C3D40000000000001402 /* SectionStateTests.swift in Sources */,
542 A1B2C3D40000000000001502 /* PortfolioDashboardTests.swift in Sources */,
539543 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */,
540544 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */,
541545 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */,
DomainDig/DashboardView.swift +22 −14
@@ -12,6 +12,14 @@ struct DashboardView: View {
1212 ]
1313
1414 var body: some View {
15 // Once per body evaluation. Each of these reads used to rebuild the
16 // whole dashboard, and there were more than twenty of them (A4).
17 let dashboard = viewModel.portfolioDashboardData
18 let visible = dashboard.filtered(
19 by: viewModel.dashboardFilter,
20 searchText: viewModel.dashboardSearchText
21 )
22
1523 List {
1624 if viewModel.trackedDomains.isEmpty {
1725 Section {
@@ -27,12 +35,12 @@ struct DashboardView: View {
2735 } else {
2836 Section {
2937 LazyVGrid(columns: summaryColumns, spacing: 10) {
30 summaryCard(title: "Total Domains", value: viewModel.portfolioDashboardData.snapshot.totalDomains, filter: .all, tint: Color(.statusInfo))
31 summaryCard(title: "Healthy", value: viewModel.portfolioDashboardData.snapshot.healthyCount, filter: .healthy, tint: Color(.statusPositive))
32 summaryCard(title: "Warning", value: viewModel.portfolioDashboardData.snapshot.warningCount, filter: .warning, tint: Color(.statusWarning))
33 summaryCard(title: "Critical", value: viewModel.portfolioDashboardData.snapshot.criticalCount, filter: .critical, tint: Color(.statusCritical))
34 summaryCard(title: "Changes (24h)", value: viewModel.portfolioDashboardData.snapshot.changedLast24h, filter: .changed, tint: Color(.statusWarning))
35 summaryCard(title: "Unreachable", value: viewModel.portfolioDashboardData.snapshot.unreachableCount, filter: .unreachable, tint: Color(.statusCritical))
38 summaryCard(title: "Total Domains", value: dashboard.snapshot.totalDomains, filter: .all, tint: Color(.statusInfo))
39 summaryCard(title: "Healthy", value: dashboard.snapshot.healthyCount, filter: .healthy, tint: Color(.statusPositive))
40 summaryCard(title: "Warning", value: dashboard.snapshot.warningCount, filter: .warning, tint: Color(.statusWarning))
41 summaryCard(title: "Critical", value: dashboard.snapshot.criticalCount, filter: .critical, tint: Color(.statusCritical))
42 summaryCard(title: "Changes (24h)", value: dashboard.snapshot.changedLast24h, filter: .changed, tint: Color(.statusWarning))
43 summaryCard(title: "Unreachable", value: dashboard.snapshot.unreachableCount, filter: .unreachable, tint: Color(.statusCritical))
3644 }
3745 .padding(.vertical, 4)
3846 }
@@ -80,10 +88,10 @@ struct DashboardView: View {
8088 .listRowBackground(Color(.appSurface))
8189
8290 Section("Recent Activity") {
83 if viewModel.filteredPortfolioRecentActivity.isEmpty {
91 if visible.recentActivity.isEmpty {
8492 dashboardEmptyRow("No recent portfolio changes")
8593 } else {
86 ForEach(viewModel.filteredPortfolioRecentActivity.prefix(8)) { item in
94 ForEach(visible.recentActivity.prefix(8)) { item in
8795 trackedDomainLink(item.trackedDomainID) {
8896 PortfolioActivityRow(item: item)
8997 }
@@ -93,10 +101,10 @@ struct DashboardView: View {
93101 .listRowBackground(Color(.appSurface))
94102
95103 Section("Attention Required") {
96 if viewModel.filteredPortfolioAttentionRequired.isEmpty {
104 if visible.attentionRequired.isEmpty {
97105 dashboardEmptyRow("Nothing urgent right now")
98106 } else {
99 ForEach(viewModel.filteredPortfolioAttentionRequired.prefix(8)) { item in
107 ForEach(visible.attentionRequired.prefix(8)) { item in
100108 trackedDomainLink(item.trackedDomainID) {
101109 PortfolioAttentionRow(item: item)
102110 }
@@ -106,10 +114,10 @@ struct DashboardView: View {
106114 .listRowBackground(Color(.appSurface))
107115
108116 Section("Expiring Soon") {
109 if viewModel.filteredPortfolioExpiringSoon.isEmpty {
117 if visible.expiringSoon.isEmpty {
110118 dashboardEmptyRow("No certificates expiring within 30 days")
111119 } else {
112 ForEach(viewModel.filteredPortfolioExpiringSoon.prefix(8)) { state in
120 ForEach(visible.expiringSoon.prefix(8)) { state in
113121 NavigationLink {
114122 TrackedDomainDetailView(viewModel: viewModel, trackedDomain: state.trackedDomain)
115123 } label: {
@@ -122,10 +130,10 @@ struct DashboardView: View {
122130 .listRowBackground(Color(.appSurface))
123131
124132 Section("Portfolio List") {
125 if viewModel.filteredPortfolioGroups.isEmpty {
133 if visible.groups.isEmpty {
126134 dashboardEmptyRow("No domains match the current filter")
127135 } else {
128 ForEach(viewModel.filteredPortfolioGroups) { group in
136 ForEach(visible.groups) { group in
129137 DisclosureGroup(
130138 isExpanded: disclosureBinding(for: group.apexDomain),
131139 content: {
DomainDig/DomainViewModel.swift +13 −196
@@ -110,66 +110,6 @@ private struct BatchLookupPayload {
110110 let snapshot: LookupSnapshot
111111}
112112
113struct PortfolioDomainStatus: Identifiable {
114 let trackedDomain: TrackedDomain
115 let latestEntry: HistoryEntry?
116 let report: DomainReport
117 let apexDomain: String
118 let health: DomainHealth
119 let lastChangeDate: Date?
120 let lastMonitoringFailure: Date?
121 let instabilityScore: Int
122 let certificateExpiryState: CertificateWarningLevel
123 let certificateDaysRemaining: Int?
124 let isUnreachable: Bool
125 let recentDNSChange: Bool
126 let recentCriticalChange: Bool
127 let recentFailureCount: Int
128
129 var id: UUID { trackedDomain.id }
130}
131
132struct PortfolioActivityItem: Identifiable {
133 let id: String
134 let trackedDomainID: UUID
135 let domain: String
136 let message: String
137 let timestamp: Date
138 let health: DomainHealth
139 let systemImage: String
140}
141
142struct PortfolioAttentionItem: Identifiable {
143 let id: String
144 let trackedDomainID: UUID
145 let domain: String
146 let reason: String
147 let timestamp: Date
148 let health: DomainHealth
149}
150
151struct PortfolioGroup: Identifiable {
152 let apexDomain: String
153 let domains: [PortfolioDomainStatus]
154
155 var id: String { apexDomain }
156}
157
158struct PortfolioDashboardData {
159 let snapshot: PortfolioSnapshot
160 let domainStates: [PortfolioDomainStatus]
161 let recentActivity: [PortfolioActivityItem]
162 let attentionRequired: [PortfolioAttentionItem]
163 let expiringSoon: [PortfolioDomainStatus]
164 let groups: [PortfolioGroup]
165}
166
167private struct PortfolioDashboardStamp: Equatable {
168 let trackedDomainSignature: [String]
169 let historySignature: [String]
170 let monitoringSignature: [String]
171}
172
173113@MainActor
174114@Observable
175115final class DomainViewModel {
@@ -323,8 +263,6 @@ final class DomainViewModel {
323263 private var trackedDomainsPersistenceDirty = false
324264 private let reportBuilder = DomainReportBuilder()
325265 private let inspectionService = DomainInspectionService()
326 private var cachedPortfolioDashboardData: PortfolioDashboardData?
327 private var cachedPortfolioDashboardStamp: PortfolioDashboardStamp?
328266 private(set) var currentResultSource: LookupResultSource = .live
329267 private(set) var currentCachedSections: [LookupSectionKind] = []
330268 private(set) var currentStatusMessage: String?
@@ -520,12 +458,17 @@ final class DomainViewModel {
520458 return sortedTrackedDomains(from: filtered, using: watchlistSortOption)
521459 }
522460
461 /// Builds the dashboard. Uncached, deliberately: the cache this replaces
462 /// was keyed on a signature of every tracked domain, the last 250 history
463 /// rows and the last 100 monitoring logs, built with
464 /// `.formatted(.number.precision(.fractionLength(3)))` — roughly 350
465 /// interpolations per access, and the dashboard reads this more than twenty
466 /// times per render, so checking the cache cost far more than the build it
467 /// was avoiding (A4).
468 ///
469 /// Callers that need it more than once should read it once and filter with
470 /// `filtered(by:searchText:)`, which is what `DashboardView` does.
523471 var portfolioDashboardData: PortfolioDashboardData {
524 let stamp = portfolioDashboardStamp()
525 if let cachedPortfolioDashboardData, cachedPortfolioDashboardStamp == stamp {
526 return cachedPortfolioDashboardData
527 }
528
529472 let domainStates = buildPortfolioDomainStates()
530473 let recentActivity = buildPortfolioActivity(from: domainStates)
531474 let attentionRequired = buildAttentionQueue(from: domainStates)
@@ -535,7 +478,7 @@ final class DomainViewModel {
535478 ($0.certificateDaysRemaining ?? .max, $0.trackedDomain.domain)
536479 < ($1.certificateDaysRemaining ?? .max, $1.trackedDomain.domain)
537480 }
538 let groups = buildPortfolioGroups(from: domainStates)
481 let groups = PortfolioDashboardData.groups(from: domainStates)
539482 let snapshot = PortfolioSnapshot(
540483 totalDomains: domainStates.count,
541484 healthyCount: domainStates.filter { $0.health == .healthy }.count,
@@ -548,7 +491,7 @@ final class DomainViewModel {
548491 expiringSoonCount: expiringSoon.count,
549492 unreachableCount: domainStates.filter(\.isUnreachable).count
550493 )
551 let data = PortfolioDashboardData(
494 return PortfolioDashboardData(
552495 snapshot: snapshot,
553496 domainStates: domainStates,
554497 recentActivity: recentActivity,
@@ -556,35 +499,6 @@ final class DomainViewModel {
556499 expiringSoon: expiringSoon,
557500 groups: groups
558501 )
559 cachedPortfolioDashboardStamp = stamp
560 cachedPortfolioDashboardData = data
561 return data
562 }
563
564 var filteredPortfolioDomainStates: [PortfolioDomainStatus] {
565 let query = dashboardSearchText.trimmingCharacters(in: .whitespacesAndNewlines)
566 return portfolioDashboardData.domainStates.filter { state in
567 matchesPortfolioFilter(state) && matchesDashboardSearch(state, query: query)
568 }
569 }
570
571 var filteredPortfolioGroups: [PortfolioGroup] {
572 buildPortfolioGroups(from: filteredPortfolioDomainStates)
573 }
574
575 var filteredPortfolioRecentActivity: [PortfolioActivityItem] {
576 let visibleDomainIDs = Set(filteredPortfolioDomainStates.map(\.trackedDomain.id))
577 return portfolioDashboardData.recentActivity.filter { visibleDomainIDs.contains($0.trackedDomainID) }
578 }
579
580 var filteredPortfolioAttentionRequired: [PortfolioAttentionItem] {
581 let visibleDomainIDs = Set(filteredPortfolioDomainStates.map(\.trackedDomain.id))
582 return portfolioDashboardData.attentionRequired.filter { visibleDomainIDs.contains($0.trackedDomainID) }
583 }
584
585 var filteredPortfolioExpiringSoon: [PortfolioDomainStatus] {
586 let visibleDomainIDs = Set(filteredPortfolioDomainStates.map(\.trackedDomain.id))
587 return portfolioDashboardData.expiringSoon.filter { visibleDomainIDs.contains($0.trackedDomain.id) }
588502 }
589503
590504 var timelineDomains: [String] {
@@ -2482,42 +2396,6 @@ final class DomainViewModel {
24822396 trackedDomains.first(where: { $0.id == id })
24832397 }
24842398
2485 private func portfolioDashboardStamp() -> PortfolioDashboardStamp {
2486 PortfolioDashboardStamp(
2487 trackedDomainSignature: trackedDomains
2488 .sorted { $0.id.uuidString < $1.id.uuidString }
2489 .map {
2490 [
2491 $0.id.uuidString,
2492 $0.updatedAt.timeIntervalSinceReferenceDate.formatted(.number.precision(.fractionLength(3))),
2493 String($0.pendingMonitoringAlerts.count),
2494 $0.lastMonitoredAt?.timeIntervalSinceReferenceDate.formatted(.number.precision(.fractionLength(3))) ?? "0",
2495 $0.lastAlertAt?.timeIntervalSinceReferenceDate.formatted(.number.precision(.fractionLength(3))) ?? "0"
2496 ].joined(separator: "|")
2497 },
2498 historySignature: history
2499 .prefix(250)
2500 .map {
2501 [
2502 $0.id.uuidString,
2503 $0.timestamp.timeIntervalSinceReferenceDate.formatted(.number.precision(.fractionLength(3))),
2504 String($0.changeCount),
2505 $0.severitySummary?.rawValue.description ?? "-"
2506 ].joined(separator: "|")
2507 },
2508 monitoringSignature: monitoringLogs
2509 .prefix(100)
2510 .map {
2511 [
2512 $0.id.uuidString,
2513 $0.timestamp.timeIntervalSinceReferenceDate.formatted(.number.precision(.fractionLength(3))),
2514 String($0.alertsTriggered),
2515 String($0.changesFound)
2516 ].joined(separator: "|")
2517 }
2518 )
2519 }
2520
25212399 private func buildPortfolioDomainStates() -> [PortfolioDomainStatus] {
25222400 let now = Date()
25232401 return sortedTrackedDomains(from: trackedDomains, using: .pinned).map { trackedDomain in
@@ -2661,7 +2539,7 @@ final class DomainViewModel {
26612539 }
26622540 .sorted { lhs, rhs in
26632541 if lhs.health != rhs.health {
2664 return healthRank(lhs.health) > healthRank(rhs.health)
2542 return lhs.health.severityRank > rhs.health.severityRank
26652543 }
26662544 return lhs.timestamp > rhs.timestamp
26672545 }
@@ -2693,56 +2571,6 @@ final class DomainViewModel {
26932571 return ("Needs attention", state.trackedDomain.updatedAt)
26942572 }
26952573
2696 private func buildPortfolioGroups(from domainStates: [PortfolioDomainStatus]) -> [PortfolioGroup] {
2697 Dictionary(grouping: domainStates, by: \.apexDomain)
2698 .map { apexDomain, domains in
2699 PortfolioGroup(
2700 apexDomain: apexDomain,
2701 domains: domains.sorted { lhs, rhs in
2702 if lhs.health != rhs.health {
2703 return healthRank(lhs.health) > healthRank(rhs.health)
2704 }
2705 return lhs.trackedDomain.domain.localizedCaseInsensitiveCompare(rhs.trackedDomain.domain) == .orderedAscending
2706 }
2707 )
2708 }
2709 .sorted { lhs, rhs in
2710 if let lhsMostSevere = lhs.domains.map(\.health).map(healthRank).max(),
2711 let rhsMostSevere = rhs.domains.map(\.health).map(healthRank).max(),
2712 lhsMostSevere != rhsMostSevere {
2713 return lhsMostSevere > rhsMostSevere
2714 }
2715 return lhs.apexDomain.localizedCaseInsensitiveCompare(rhs.apexDomain) == .orderedAscending
2716 }
2717 }
2718
2719 private func matchesPortfolioFilter(_ state: PortfolioDomainStatus) -> Bool {
2720 switch dashboardFilter {
2721 case .all:
2722 return true
2723 case .healthy:
2724 return state.health == .healthy
2725 case .warning:
2726 return state.health == .warning
2727 case .critical:
2728 return state.health == .critical
2729 case .changed:
2730 guard let lastChangeDate = state.lastChangeDate else { return false }
2731 return Date().timeIntervalSince(lastChangeDate) <= 24 * 60 * 60
2732 case .expiring:
2733 return state.certificateExpiryState != .none
2734 case .unreachable:
2735 return state.isUnreachable
2736 }
2737 }
2738
2739 private func matchesDashboardSearch(_ state: PortfolioDomainStatus, query: String) -> Bool {
2740 guard !query.isEmpty else { return true }
2741 let normalizedQuery = query.lowercased()
2742 return state.trackedDomain.domain.lowercased().contains(normalizedQuery)
2743 || state.apexDomain.lowercased().contains(normalizedQuery)
2744 }
2745
27462574 private func portfolioHistoryMessage(for entry: HistoryEntry) -> String {
27472575 guard let summary = entry.changeSummary else {
27482576 return "Configuration changed for \(entry.domain)"
@@ -2811,17 +2639,6 @@ final class DomainViewModel {
28112639 return parts.suffix(2).joined(separator: ".")
28122640 }
28132641
2814 private func healthRank(_ health: DomainHealth) -> Int {
2815 switch health {
2816 case .healthy:
2817 return 0
2818 case .warning:
2819 return 1
2820 case .critical:
2821 return 2
2822 }
2823 }
2824
28252642 private func exportSnapshots(for domains: [TrackedDomain]) -> [LookupSnapshot] {
28262643 let latestEntries = latestSnapshots(for: domains)
28272644
DomainDig/PortfolioDashboard.swift added +151
@@ -0,0 +1,151 @@
1import Foundation
2
3// The portfolio dashboard's value types and the filtering that derives a
4// visible subset from them. Split out of DomainViewModel.swift (A13), where
5// they sat above the class; the filtering arrived there with A4 and belongs
6// with the data rather than with the view model.
7
8struct PortfolioDomainStatus: Identifiable {
9 let trackedDomain: TrackedDomain
10 let latestEntry: HistoryEntry?
11 let report: DomainReport
12 let apexDomain: String
13 let health: DomainHealth
14 let lastChangeDate: Date?
15 let lastMonitoringFailure: Date?
16 let instabilityScore: Int
17 let certificateExpiryState: CertificateWarningLevel
18 let certificateDaysRemaining: Int?
19 let isUnreachable: Bool
20 let recentDNSChange: Bool
21 let recentCriticalChange: Bool
22 let recentFailureCount: Int
23
24 var id: UUID { trackedDomain.id }
25}
26
27struct PortfolioActivityItem: Identifiable {
28 let id: String
29 let trackedDomainID: UUID
30 let domain: String
31 let message: String
32 let timestamp: Date
33 let health: DomainHealth
34 let systemImage: String
35}
36
37struct PortfolioAttentionItem: Identifiable {
38 let id: String
39 let trackedDomainID: UUID
40 let domain: String
41 let reason: String
42 let timestamp: Date
43 let health: DomainHealth
44}
45
46struct PortfolioGroup: Identifiable {
47 let apexDomain: String
48 let domains: [PortfolioDomainStatus]
49
50 var id: String { apexDomain }
51}
52
53struct PortfolioDashboardData {
54 let snapshot: PortfolioSnapshot
55 let domainStates: [PortfolioDomainStatus]
56 let recentActivity: [PortfolioActivityItem]
57 let attentionRequired: [PortfolioAttentionItem]
58 let expiringSoon: [PortfolioDomainStatus]
59 let groups: [PortfolioGroup]
60
61 /// The same dashboard narrowed to the domains matching the filter and the
62 /// search text, with every list kept consistent with that set.
63 ///
64 /// This used to be five computed properties on the view model, each of
65 /// which re-read `portfolioDashboardData` and re-derived the visible set.
66 /// A4: the view reads each of them twice, so the dashboard was rebuilt
67 /// more than twenty times per render. Filtering is a function of the data
68 /// now, so a view can do it once.
69 func filtered(by filter: PortfolioFilterOption, searchText: String) -> PortfolioDashboardData {
70 let query = searchText.trimmingCharacters(in: .whitespacesAndNewlines)
71 let visibleStates = domainStates.filter {
72 $0.matches(filter) && $0.matches(searchQuery: query)
73 }
74 let visibleIDs = Set(visibleStates.map(\.trackedDomain.id))
75
76 return PortfolioDashboardData(
77 snapshot: snapshot,
78 domainStates: visibleStates,
79 recentActivity: recentActivity.filter { visibleIDs.contains($0.trackedDomainID) },
80 attentionRequired: attentionRequired.filter { visibleIDs.contains($0.trackedDomainID) },
81 expiringSoon: expiringSoon.filter { visibleIDs.contains($0.trackedDomain.id) },
82 groups: PortfolioDashboardData.groups(from: visibleStates)
83 )
84 }
85
86 /// Worst health first, then alphabetical, within a group and between them.
87 static func groups(from domainStates: [PortfolioDomainStatus]) -> [PortfolioGroup] {
88 Dictionary(grouping: domainStates, by: \.apexDomain)
89 .map { apexDomain, domains in
90 PortfolioGroup(
91 apexDomain: apexDomain,
92 domains: domains.sorted { lhs, rhs in
93 if lhs.health != rhs.health {
94 return lhs.health.severityRank > rhs.health.severityRank
95 }
96 return lhs.trackedDomain.domain
97 .localizedCaseInsensitiveCompare(rhs.trackedDomain.domain) == .orderedAscending
98 }
99 )
100 }
101 .sorted { lhs, rhs in
102 if let lhsMostSevere = lhs.domains.map(\.health.severityRank).max(),
103 let rhsMostSevere = rhs.domains.map(\.health.severityRank).max(),
104 lhsMostSevere != rhsMostSevere {
105 return lhsMostSevere > rhsMostSevere
106 }
107 return lhs.apexDomain.localizedCaseInsensitiveCompare(rhs.apexDomain) == .orderedAscending
108 }
109 }
110}
111
112extension DomainHealth {
113 /// Sort order for "worst first" listings. Was a private `healthRank` on the
114 /// view model, which is the wrong owner for a property of the health value.
115 var severityRank: Int {
116 switch self {
117 case .healthy: return 0
118 case .warning: return 1
119 case .critical: return 2
120 }
121 }
122}
123
124extension PortfolioDomainStatus {
125 func matches(_ filter: PortfolioFilterOption) -> Bool {
126 switch filter {
127 case .all:
128 return true
129 case .healthy:
130 return health == .healthy
131 case .warning:
132 return health == .warning
133 case .critical:
134 return health == .critical
135 case .changed:
136 guard let lastChangeDate else { return false }
137 return Date().timeIntervalSince(lastChangeDate) <= 24 * 60 * 60
138 case .expiring:
139 return certificateExpiryState != .none
140 case .unreachable:
141 return isUnreachable
142 }
143 }
144
145 func matches(searchQuery query: String) -> Bool {
146 guard !query.isEmpty else { return true }
147 let normalized = query.lowercased()
148 return trackedDomain.domain.lowercased().contains(normalized)
149 || apexDomain.lowercased().contains(normalized)
150 }
151}
DomainDigTests/PortfolioDashboardTests.swift added +262
@@ -0,0 +1,262 @@
1import XCTest
2@testable import DomainDig
3
4/// Filtering the dashboard used to be five computed properties on the view
5/// model, each re-reading `portfolioDashboardData` and re-deriving the visible
6/// set — so the whole dashboard was rebuilt more than twenty times per render
7/// (A4), and none of it was covered.
8///
9/// It is a function of the data now, which makes it testable, and these are
10/// what that bought.
11final class PortfolioDashboardTests: XCTestCase {
12
13 private func state(
14 domain: String,
15 apex: String? = nil,
16 health: DomainHealth = .healthy,
17 lastChangeDate: Date? = nil,
18 certificateExpiry: CertificateWarningLevel = .none,
19 certificateDaysRemaining: Int? = nil,
20 isUnreachable: Bool = false
21 ) -> PortfolioDomainStatus {
22 PortfolioDomainStatus(
23 trackedDomain: TrackedDomain(domain: domain, createdAt: Date(), updatedAt: Date()),
24 latestEntry: nil,
25 report: SnapshotFixture.report(domain: domain),
26 apexDomain: apex ?? domain,
27 health: health,
28 lastChangeDate: lastChangeDate,
29 lastMonitoringFailure: nil,
30 instabilityScore: 0,
31 certificateExpiryState: certificateExpiry,
32 certificateDaysRemaining: certificateDaysRemaining,
33 isUnreachable: isUnreachable,
34 recentDNSChange: false,
35 recentCriticalChange: false,
36 recentFailureCount: 0
37 )
38 }
39
40 private func dashboard(_ states: [PortfolioDomainStatus]) -> PortfolioDashboardData {
41 PortfolioDashboardData(
42 snapshot: PortfolioSnapshot(
43 totalDomains: states.count,
44 healthyCount: states.filter { $0.health == .healthy }.count,
45 warningCount: states.filter { $0.health == .warning }.count,
46 criticalCount: states.filter { $0.health == .critical }.count,
47 changedLast24h: 0,
48 expiringSoonCount: states.filter { $0.certificateExpiryState != .none }.count,
49 unreachableCount: states.filter(\.isUnreachable).count
50 ),
51 domainStates: states,
52 recentActivity: states.map {
53 PortfolioActivityItem(
54 id: "activity-\($0.trackedDomain.domain)",
55 trackedDomainID: $0.trackedDomain.id,
56 domain: $0.trackedDomain.domain,
57 message: "changed",
58 timestamp: Date(),
59 health: $0.health,
60 systemImage: "circle"
61 )
62 },
63 attentionRequired: states.map {
64 PortfolioAttentionItem(
65 id: "attention-\($0.trackedDomain.domain)",
66 trackedDomainID: $0.trackedDomain.id,
67 domain: $0.trackedDomain.domain,
68 reason: "needs attention",
69 timestamp: Date(),
70 health: $0.health
71 )
72 },
73 expiringSoon: states.filter { $0.certificateExpiryState != .none },
74 groups: PortfolioDashboardData.groups(from: states)
75 )
76 }
77
78 // MARK: Filters
79
80 func testTheAllFilterKeepsEveryDomain() {
81 let data = dashboard([
82 state(domain: "a.example", health: .healthy),
83 state(domain: "b.example", health: .critical)
84 ])
85
86 let visible = data.filtered(by: .all, searchText: "")
87
88 XCTAssertEqual(visible.domainStates.map(\.trackedDomain.domain), ["a.example", "b.example"])
89 }
90
91 func testEachHealthFilterKeepsOnlyThatHealth() {
92 let data = dashboard([
93 state(domain: "healthy.example", health: .healthy),
94 state(domain: "warning.example", health: .warning),
95 state(domain: "critical.example", health: .critical)
96 ])
97
98 XCTAssertEqual(
99 data.filtered(by: .healthy, searchText: "").domainStates.map(\.trackedDomain.domain),
100 ["healthy.example"]
101 )
102 XCTAssertEqual(
103 data.filtered(by: .warning, searchText: "").domainStates.map(\.trackedDomain.domain),
104 ["warning.example"]
105 )
106 XCTAssertEqual(
107 data.filtered(by: .critical, searchText: "").domainStates.map(\.trackedDomain.domain),
108 ["critical.example"]
109 )
110 }
111
112 func testTheUnreachableFilterKeepsOnlyUnreachableDomains() {
113 let data = dashboard([
114 state(domain: "up.example"),
115 state(domain: "down.example", isUnreachable: true)
116 ])
117
118 XCTAssertEqual(
119 data.filtered(by: .unreachable, searchText: "").domainStates.map(\.trackedDomain.domain),
120 ["down.example"]
121 )
122 }
123
124 func testTheExpiringFilterKeepsAnyNonNoneWarningLevel() {
125 let data = dashboard([
126 state(domain: "fine.example", certificateExpiry: .none),
127 state(domain: "soon.example", certificateExpiry: .warning),
128 state(domain: "urgent.example", certificateExpiry: .critical)
129 ])
130
131 XCTAssertEqual(
132 Set(data.filtered(by: .expiring, searchText: "").domainStates.map(\.trackedDomain.domain)),
133 ["soon.example", "urgent.example"]
134 )
135 }
136
137 /// The 24-hour window is relative to now, so a change from last week is not
138 /// "changed" and one from a minute ago is.
139 func testTheChangedFilterUsesATwentyFourHourWindow() {
140 let data = dashboard([
141 state(domain: "recent.example", lastChangeDate: Date().addingTimeInterval(-60)),
142 state(domain: "old.example", lastChangeDate: Date().addingTimeInterval(-8 * 24 * 60 * 60)),
143 state(domain: "never.example", lastChangeDate: nil)
144 ])
145
146 XCTAssertEqual(
147 data.filtered(by: .changed, searchText: "").domainStates.map(\.trackedDomain.domain),
148 ["recent.example"]
149 )
150 }
151
152 // MARK: Search
153
154 func testSearchMatchesTheDomainAndTheApexCaseInsensitively() {
155 let data = dashboard([
156 state(domain: "shop.example.com", apex: "example.com"),
157 state(domain: "other.test", apex: "other.test")
158 ])
159
160 XCTAssertEqual(
161 data.filtered(by: .all, searchText: "SHOP").domainStates.map(\.trackedDomain.domain),
162 ["shop.example.com"]
163 )
164 XCTAssertEqual(
165 data.filtered(by: .all, searchText: "example.com").domainStates.map(\.trackedDomain.domain),
166 ["shop.example.com"]
167 )
168 }
169
170 func testSearchIgnoresSurroundingWhitespace() {
171 let data = dashboard([state(domain: "a.example"), state(domain: "b.example")])
172
173 XCTAssertEqual(
174 data.filtered(by: .all, searchText: " ").domainStates.count, 2,
175 "a whitespace-only query should not filter anything out"
176 )
177 XCTAssertEqual(
178 data.filtered(by: .all, searchText: " a. ").domainStates.map(\.trackedDomain.domain),
179 ["a.example"],
180 "the query is trimmed at the ends, so this matches as 'a.'"
181 )
182 }
183
184 func testTheFilterAndTheSearchBothApply() {
185 let data = dashboard([
186 state(domain: "bad.example", health: .critical),
187 state(domain: "bad.other", health: .healthy),
188 state(domain: "good.example", health: .critical)
189 ])
190
191 XCTAssertEqual(
192 data.filtered(by: .critical, searchText: "bad").domainStates.map(\.trackedDomain.domain),
193 ["bad.example"]
194 )
195 }
196
197 // MARK: The dependent lists follow the visible set
198
199 /// Each list used to be filtered by its own computed property against a
200 /// separately rebuilt dashboard. They have to agree.
201 func testEveryListIsNarrowedToTheVisibleDomains() {
202 let data = dashboard([
203 state(domain: "keep.example", health: .critical, certificateExpiry: .warning),
204 state(domain: "drop.example", health: .healthy, certificateExpiry: .warning)
205 ])
206
207 let visible = data.filtered(by: .critical, searchText: "")
208
209 XCTAssertEqual(visible.domainStates.map(\.trackedDomain.domain), ["keep.example"])
210 XCTAssertEqual(visible.recentActivity.map(\.domain), ["keep.example"])
211 XCTAssertEqual(visible.attentionRequired.map(\.domain), ["keep.example"])
212 XCTAssertEqual(visible.expiringSoon.map(\.trackedDomain.domain), ["keep.example"])
213 XCTAssertEqual(visible.groups.flatMap { $0.domains.map(\.trackedDomain.domain) }, ["keep.example"])
214 }
215
216 /// The snapshot counts describe the whole portfolio, not the filtered view —
217 /// the summary cards are what the filter is selected *from*, so filtering
218 /// must not change them.
219 func testFilteringDoesNotChangeTheSummaryCounts() {
220 let data = dashboard([
221 state(domain: "a.example", health: .healthy),
222 state(domain: "b.example", health: .critical)
223 ])
224
225 let visible = data.filtered(by: .critical, searchText: "")
226
227 XCTAssertEqual(visible.snapshot.totalDomains, 2)
228 XCTAssertEqual(visible.snapshot.healthyCount, 1)
229 XCTAssertEqual(visible.snapshot.criticalCount, 1)
230 }
231
232 // MARK: Grouping
233
234 func testGroupsPutTheWorstHealthFirst() {
235 let groups = PortfolioDashboardData.groups(from: [
236 state(domain: "a.calm", apex: "calm", health: .healthy),
237 state(domain: "b.bad", apex: "bad", health: .critical),
238 state(domain: "c.mid", apex: "mid", health: .warning)
239 ])
240
241 XCTAssertEqual(groups.map(\.apexDomain), ["bad", "mid", "calm"])
242 }
243
244 func testDomainsWithinAGroupAreWorstFirstThenAlphabetical() {
245 let groups = PortfolioDashboardData.groups(from: [
246 state(domain: "z.example", apex: "example", health: .healthy),
247 state(domain: "a.example", apex: "example", health: .healthy),
248 state(domain: "m.example", apex: "example", health: .critical)
249 ])
250
251 XCTAssertEqual(groups.count, 1)
252 XCTAssertEqual(
253 groups[0].domains.map(\.trackedDomain.domain),
254 ["m.example", "a.example", "z.example"]
255 )
256 }
257
258 func testHealthSeverityRankOrdersWorstHighest() {
259 XCTAssertLessThan(DomainHealth.healthy.severityRank, DomainHealth.warning.severityRank)
260 XCTAssertLessThan(DomainHealth.warning.severityRank, DomainHealth.critical.severityRank)
261 }
262}