Commit 0b4b200f53

0b4b200f536269c56418598ef8ec1300886c864a

parent: be76f79456

Unsigned

cmc <hello@cleberg.net> · 2026-10-25 04:55 UTC

Collapse each section's state into one value (!30)

A2, and the last of W6.

Each inspection section was three independent stored properties — a value, a
`*Loading` flag and a `*Error` string. 20 flags and 19 error strings, with
nothing tying each trio together: a section could be left loading forever
because one of three assignments was missed, or report an error while still
claiming to load. `SectionState<Value>` holds the three as one stored property
per section.

## The tests came first

They were green before the collapse and are unchanged after — that was the
point of writing them, and it is why this was worth attempting at all. They
assert the section slices the views consume rather than the raw properties, so
they outlive the representation they were written against.

11 tests on what each card ends up showing: every section settling after a
snapshot lands, `resultsLoaded` false before any lookup, one failure not
marking the others failed, each card carrying its own message, a value and an
error together, and a new lookup clearing the previous domain's results.
`applySnapshot` is internal so they reach it without a live lookup.

## Not an exclusive enum

The finding proposed `idle | loading | loaded | failed`. That cannot work here:
a section really can have both a value and an error — the TLS card renders a
stale certificate next to a handshake error, and `AppStatusFactory.tls` takes
`sslInfo` and `error` together. An exclusive enum would have to drop one of
them. `testAnErrorAndAValueTogetherKeepBothReachable` pins it.

So `SectionState` groups the three with a `SectionPhase` saying whether the
section is still moving. That fixes what was actually broken — three things
that could disagree — without pretending the data is narrower than it is.

## What the collapse paid for

- `loadLookup` took three `ReferenceWritableKeyPath`s per section. It takes one.
- `setAllLoadingStates` and `clearLookupState` are one assignment per section
  instead of three; `clearLookupState` went from 67 lines to 30.
- `resultsLoaded` asks each section whether it settled instead of negating
  fifteen loading flags.

Net on the view model: 243 deletions against 214 insertions.

## The accessors are a staging layer

`dnsSections`, `dnsLoading`, `dnsError` and the rest survive as computed
accessors over the stored state, so nothing outside the view model changed and
the diff stays reviewable. The next step is views reading the state directly,
as the Web and Network slices from !29 already do.

## A12, found writing the tests

`currentSnapshot` reads `provenanceBySection` from the *saved history entry*,
not from the snapshot just applied, and `applySnapshot` stores it nowhere. A
lookup that ends with a status message returns before saving, so a partial or
failed lookup shows no provenance for any section — the case where the source
matters most. Recorded as a finding; the test pins the behaviour as it is so a
fix can change it deliberately.

## Verification

Both tiers: 244 tests, 0 failures on iOS 18.6 (iPhone 16) and iOS 27.0
(iPhone Air).

Layout: unified · split

DomainDig.xcodeproj/project.pbxproj +4
@@ -34,6 +34,7 @@
34 A1B2C3D40000000000001002 /* DomainViewModelStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001001 /* DomainViewModelStoreTests.swift */; }; 34 A1B2C3D40000000000001002 /* DomainViewModelStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001001 /* DomainViewModelStoreTests.swift */; };
35 A1B2C3D40000000000001102 /* LookupCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001101 /* LookupCacheTests.swift */; }; 35 A1B2C3D40000000000001102 /* LookupCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001101 /* LookupCacheTests.swift */; };
36 A1B2C3D40000000000001202 /* HistoryStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001201 /* HistoryStoreTests.swift */; }; 36 A1B2C3D40000000000001202 /* HistoryStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001201 /* HistoryStoreTests.swift */; };
37 A1B2C3D40000000000001402 /* SectionStateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001401 /* SectionStateTests.swift */; };
37 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000301 /* AvailabilityTests.swift */; }; 38 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000301 /* AvailabilityTests.swift */; };
38 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */; }; 39 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */; };
39 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000501 /* DomainNameTests.swift */; }; 40 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000501 /* DomainNameTests.swift */; };
@@ -115,6 +116,7 @@
115 A1B2C3D40000000000001001 /* DomainViewModelStoreTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainViewModelStoreTests.swift; sourceTree = "<group>"; }; 116 A1B2C3D40000000000001001 /* DomainViewModelStoreTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainViewModelStoreTests.swift; sourceTree = "<group>"; };
116 A1B2C3D40000000000001101 /* LookupCacheTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = LookupCacheTests.swift; sourceTree = "<group>"; }; 117 A1B2C3D40000000000001101 /* LookupCacheTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = LookupCacheTests.swift; sourceTree = "<group>"; };
117 A1B2C3D40000000000001201 /* HistoryStoreTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HistoryStoreTests.swift; sourceTree = "<group>"; }; 118 A1B2C3D40000000000001201 /* HistoryStoreTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HistoryStoreTests.swift; sourceTree = "<group>"; };
119 A1B2C3D40000000000001401 /* SectionStateTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SectionStateTests.swift; sourceTree = "<group>"; };
118 A1B2C3D40000000000000301 /* AvailabilityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AvailabilityTests.swift; sourceTree = "<group>"; }; 120 A1B2C3D40000000000000301 /* AvailabilityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AvailabilityTests.swift; sourceTree = "<group>"; };
119 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudSyncMergeTests.swift; sourceTree = "<group>"; }; 121 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudSyncMergeTests.swift; sourceTree = "<group>"; };
120 A1B2C3D40000000000000501 /* DomainNameTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainNameTests.swift; sourceTree = "<group>"; }; 122 A1B2C3D40000000000000501 /* DomainNameTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainNameTests.swift; sourceTree = "<group>"; };
@@ -261,6 +263,7 @@
261 A1B2C3D40000000000001001 /* DomainViewModelStoreTests.swift */, 263 A1B2C3D40000000000001001 /* DomainViewModelStoreTests.swift */,
262 A1B2C3D40000000000001101 /* LookupCacheTests.swift */, 264 A1B2C3D40000000000001101 /* LookupCacheTests.swift */,
263 A1B2C3D40000000000001201 /* HistoryStoreTests.swift */, 265 A1B2C3D40000000000001201 /* HistoryStoreTests.swift */,
266 A1B2C3D40000000000001401 /* SectionStateTests.swift */,
264 A1B2C3D40000000000000301 /* AvailabilityTests.swift */, 267 A1B2C3D40000000000000301 /* AvailabilityTests.swift */,
265 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */, 268 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */,
266 A1B2C3D40000000000000501 /* DomainNameTests.swift */, 269 A1B2C3D40000000000000501 /* DomainNameTests.swift */,
@@ -532,6 +535,7 @@
532 A1B2C3D40000000000001002 /* DomainViewModelStoreTests.swift in Sources */, 535 A1B2C3D40000000000001002 /* DomainViewModelStoreTests.swift in Sources */,
533 A1B2C3D40000000000001102 /* LookupCacheTests.swift in Sources */, 536 A1B2C3D40000000000001102 /* LookupCacheTests.swift in Sources */,
534 A1B2C3D40000000000001202 /* HistoryStoreTests.swift in Sources */, 537 A1B2C3D40000000000001202 /* HistoryStoreTests.swift in Sources */,
538 A1B2C3D40000000000001402 /* SectionStateTests.swift in Sources */,
535 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */, 539 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */,
536 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */, 540 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */,
537 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */, 541 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */,
DomainDig/DomainViewModel.swift +218 −247
@@ -177,78 +177,118 @@ final class DomainViewModel {
177 var bulkInput: String = "" 177 var bulkInput: String = ""
178 var domainInputError: String? 178 var domainInputError: String?
179 179
180 var dnsSections: [DNSSection] = [] 180 // MARK: Section state
181 var dnsLoading = false 181
182 var dnsError: String? 182 /// Each section's value, phase and error as one stored property, so the
183 var availabilityResult: DomainAvailabilityResult? 183 /// three are written together or not at all. There were 20 `*Loading`
184 var availabilityLoading = false 184 /// flags and 19 `*Error` strings before, independently assignable (A2).
185 var suggestions: [DomainSuggestionResult] = [] 185 ///
186 var suggestionsLoading = false 186 /// The accessors below keep the names every reader already uses. They are
187 187 /// a staging layer: the next step is views reading the state directly, as
188 var sslInfo: SSLCertificateInfo? 188 /// the Web and Network slices already do.
189 var sslLoading = false 189 var dnsState = SectionState<[DNSSection]>()
190 var sslError: String? 190 var availabilityState = SectionState<DomainAvailabilityResult>()
191 var hstsPreloaded: Bool? 191 var suggestionsState = SectionState<[DomainSuggestionResult]>()
192 var hstsLoading = false 192 var sslState = SectionState<SSLCertificateInfo>()
193 193 var hstsState = SectionState<Bool>()
194 var httpHeaders: [HTTPHeader] = [] 194 var httpHeadersState = SectionState<[HTTPHeader]>()
195 var reachabilityState = SectionState<[PortReachability]>()
196 var ipGeolocationState = SectionState<IPGeolocation>()
197 var emailSecurityState = SectionState<EmailSecurityResult>()
198 var ownershipState = SectionState<DomainOwnership>()
199 var ownershipHistoryState = SectionState<[DomainOwnershipHistoryEvent]>()
200 var ptrState = SectionState<String>()
201 var redirectChainState = SectionState<[RedirectHop]>()
202 var subdomainsState = SectionState<[DiscoveredSubdomain]>()
203 var extendedSubdomainsState = SectionState<[DiscoveredSubdomain]>()
204 var dnsHistoryState = SectionState<[DNSHistoryEvent]>()
205 var domainPricingState = SectionState<DomainPricingInsight>()
206 var reputationState = SectionState<DomainReputationResult>()
207 var portScanState = SectionState<[PortScanResult]>()
208 var customPortScanState = SectionState<[PortScanResult]>()
209
210 var dnsSections: [DNSSection] { dnsState.items }
211 var dnsLoading: Bool { dnsState.isLoading }
212 var dnsError: String? { dnsState.error }
213
214 var availabilityResult: DomainAvailabilityResult? { availabilityState.value }
215 var availabilityLoading: Bool { availabilityState.isLoading }
216
217 var suggestions: [DomainSuggestionResult] { suggestionsState.items }
218 var suggestionsLoading: Bool { suggestionsState.isLoading }
219
220 var sslInfo: SSLCertificateInfo? { sslState.value }
221 var sslLoading: Bool { sslState.isLoading }
222 var sslError: String? { sslState.error }
223
224 var hstsPreloaded: Bool? { hstsState.value }
225 var hstsLoading: Bool { hstsState.isLoading }
226
227 var httpHeaders: [HTTPHeader] { httpHeadersState.items }
228 var httpHeadersLoading: Bool { httpHeadersState.isLoading }
229 var httpHeadersError: String? { httpHeadersState.error }
230
231 var reachabilityResults: [PortReachability] { reachabilityState.items }
232 var reachabilityLoading: Bool { reachabilityState.isLoading }
233 var reachabilityError: String? { reachabilityState.error }
234
235 var ipGeolocation: IPGeolocation? { ipGeolocationState.value }
236 var ipGeolocationLoading: Bool { ipGeolocationState.isLoading }
237 var ipGeolocationError: String? { ipGeolocationState.error }
238
239 var emailSecurity: EmailSecurityResult? { emailSecurityState.value }
240 var emailSecurityLoading: Bool { emailSecurityState.isLoading }
241 var emailSecurityError: String? { emailSecurityState.error }
242
243 var ownershipResult: DomainOwnership? { ownershipState.value }
244 var ownershipLoading: Bool { ownershipState.isLoading }
245 var ownershipError: String? { ownershipState.error }
246
247 var ownershipHistory: [DomainOwnershipHistoryEvent] { ownershipHistoryState.items }
248 var ownershipHistoryLoading: Bool { ownershipHistoryState.isLoading }
249 var ownershipHistoryError: String? { ownershipHistoryState.error }
250
251 var ptrRecord: String? { ptrState.value }
252 var ptrLoading: Bool { ptrState.isLoading }
253 var ptrError: String? { ptrState.error }
254
255 var redirectChain: [RedirectHop] { redirectChainState.items }
256 var redirectChainLoading: Bool { redirectChainState.isLoading }
257 var redirectChainError: String? { redirectChainState.error }
258
259 var subdomains: [DiscoveredSubdomain] { subdomainsState.items }
260 var subdomainsLoading: Bool { subdomainsState.isLoading }
261 var subdomainsError: String? { subdomainsState.error }
262
263 var extendedSubdomains: [DiscoveredSubdomain] { extendedSubdomainsState.items }
264 var extendedSubdomainsLoading: Bool { extendedSubdomainsState.isLoading }
265 var extendedSubdomainsError: String? { extendedSubdomainsState.error }
266
267 var dnsHistory: [DNSHistoryEvent] { dnsHistoryState.items }
268 var dnsHistoryLoading: Bool { dnsHistoryState.isLoading }
269 var dnsHistoryError: String? { dnsHistoryState.error }
270
271 var domainPricing: DomainPricingInsight? { domainPricingState.value }
272 var domainPricingLoading: Bool { domainPricingState.isLoading }
273 var domainPricingError: String? { domainPricingState.error }
274
275 var reputation: DomainReputationResult? { reputationState.value }
276 var reputationLoading: Bool { reputationState.isLoading }
277 var reputationError: String? { reputationState.error }
278
279 var portScanResults: [PortScanResult] { portScanState.items }
280 var portScanLoading: Bool { portScanState.isLoading }
281 var portScanError: String? { portScanState.error }
282
283 var customPortResults: [PortScanResult] { customPortScanState.items }
284 var customPortScanLoading: Bool { customPortScanState.isLoading }
285 var customPortScanError: String? { customPortScanState.error }
286
195 var httpSecurityGrade: String? 287 var httpSecurityGrade: String?
196 var httpStatusCode: Int? 288 var httpStatusCode: Int?
197 var httpResponseTimeMs: Int? 289 var httpResponseTimeMs: Int?
198 var httpProtocol: String? 290 var httpProtocol: String?
199 var http3Advertised = false 291 var http3Advertised = false
200 var httpHeadersLoading = false
201 var httpHeadersError: String?
202
203 var reachabilityResults: [PortReachability] = []
204 var reachabilityLoading = false
205 var reachabilityError: String?
206
207 var ipGeolocation: IPGeolocation?
208 var ipGeolocationLoading = false
209 var ipGeolocationError: String?
210
211 var emailSecurity: EmailSecurityResult?
212 var emailSecurityLoading = false
213 var emailSecurityError: String?
214
215 var ownershipResult: DomainOwnership?
216 var ownershipLoading = false
217 var ownershipError: String?
218 var ownershipHistory: [DomainOwnershipHistoryEvent] = []
219 var ownershipHistoryLoading = false
220 var ownershipHistoryError: String?
221
222 var ptrRecord: String?
223 var ptrLoading = false
224 var ptrError: String?
225
226 var redirectChain: [RedirectHop] = []
227 var redirectChainLoading = false
228 var redirectChainError: String?
229
230 var subdomains: [DiscoveredSubdomain] = []
231 var subdomainsLoading = false
232 var subdomainsError: String?
233 var extendedSubdomains: [DiscoveredSubdomain] = []
234 var extendedSubdomainsLoading = false
235 var extendedSubdomainsError: String?
236 var dnsHistory: [DNSHistoryEvent] = []
237 var dnsHistoryLoading = false
238 var dnsHistoryError: String?
239 var domainPricing: DomainPricingInsight?
240 var domainPricingLoading = false
241 var domainPricingError: String?
242 var reputation: DomainReputationResult?
243 var reputationLoading = false
244 var reputationError: String?
245
246 var portScanResults: [PortScanResult] = []
247 var portScanLoading = false
248 var portScanError: String?
249 var customPortResults: [PortScanResult] = []
250 var customPortScanLoading = false
251 var customPortScanError: String?
252 292
253 var hasRun = false 293 var hasRun = false
254 private(set) var searchedDomain: String = "" 294 private(set) var searchedDomain: String = ""
@@ -372,22 +412,24 @@ final class DomainViewModel {
372 } 412 }
373 413
374 var resultsLoaded: Bool { 414 var resultsLoaded: Bool {
375 hasRun && 415 guard hasRun else { return false }
376 !dnsLoading && 416 return [
377 !availabilityLoading && 417 dnsState.isSettled,
378 !suggestionsLoading && 418 availabilityState.isSettled,
379 !sslLoading && 419 suggestionsState.isSettled,
380 !hstsLoading && 420 sslState.isSettled,
381 !httpHeadersLoading && 421 hstsState.isSettled,
382 !reachabilityLoading && 422 httpHeadersState.isSettled,
383 !ipGeolocationLoading && 423 reachabilityState.isSettled,
384 !emailSecurityLoading && 424 ipGeolocationState.isSettled,
385 !ownershipLoading && 425 emailSecurityState.isSettled,
386 !ptrLoading && 426 ownershipState.isSettled,
387 !redirectChainLoading && 427 ptrState.isSettled,
388 !subdomainsLoading && 428 redirectChainState.isSettled,
389 !portScanLoading && 429 subdomainsState.isSettled,
390 !customPortScanLoading 430 portScanState.isSettled,
431 !customPortScanState.isLoading
432 ].allSatisfy { $0 }
391 } 433 }
392 434
393 var activeLoadingLabels: [String] { 435 var activeLoadingLabels: [String] {
@@ -1327,13 +1369,12 @@ final class DomainViewModel {
1327 1369
1328 func runCustomPortScan(ports: [UInt16]) async { 1370 func runCustomPortScan(ports: [UInt16]) async {
1329 guard !searchedDomain.isEmpty else { 1371 guard !searchedDomain.isEmpty else {
1330 customPortScanError = "Run a domain lookup first" 1372 customPortScanState = .settled(value: [], error: "Run a domain lookup first")
1331 return 1373 return
1332 } 1374 }
1333 1375
1334 guard !ports.isEmpty else { 1376 guard !ports.isEmpty else {
1335 customPortScanError = "Enter at least one valid port" 1377 customPortScanState = .settled(value: [], error: "Enter at least one valid port")
1336 customPortResults = []
1337 return 1378 return
1338 } 1379 }
1339 1380
@@ -1341,9 +1382,7 @@ final class DomainViewModel {
1341 let domain = searchedDomain 1382 let domain = searchedDomain
1342 let lookupID = activeLookupID 1383 let lookupID = activeLookupID
1343 1384
1344 customPortScanLoading = true 1385 customPortScanState = .loading
1345 customPortScanError = nil
1346 customPortResults = []
1347 1386
1348 customPortScanTask = Task { [weak self] in 1387 customPortScanTask = Task { [weak self] in
1349 guard let self else { return } 1388 guard let self else { return }
@@ -1407,8 +1446,7 @@ final class DomainViewModel {
1407 } 1446 }
1408 1447
1409 func loadOwnershipHistory() async { 1448 func loadOwnershipHistory() async {
1410 await loadLookup(into: \.ownershipHistory, loading: \.ownershipHistoryLoading, error: \.ownershipHistoryError, 1449 await loadLookup(into: \.ownershipHistoryState, fallback: "Ownership history unavailable") {
1411 fallback: "Ownership history unavailable") {
1412 await ExternalDataService.shared.ownershipHistory( 1450 await ExternalDataService.shared.ownershipHistory(
1413 domain: searchedDomain, 1451 domain: searchedDomain,
1414 currentOwnership: ownershipResult, 1452 currentOwnership: ownershipResult,
@@ -1418,8 +1456,7 @@ final class DomainViewModel {
1418 } 1456 }
1419 1457
1420 func loadDNSHistory() async { 1458 func loadDNSHistory() async {
1421 await loadLookup(into: \.dnsHistory, loading: \.dnsHistoryLoading, error: \.dnsHistoryError, 1459 await loadLookup(into: \.dnsHistoryState, fallback: "DNS history unavailable") {
1422 fallback: "DNS history unavailable") {
1423 await ExternalDataService.shared.dnsHistory( 1460 await ExternalDataService.shared.dnsHistory(
1424 domain: searchedDomain, 1461 domain: searchedDomain,
1425 dnsSections: dnsSections, 1462 dnsSections: dnsSections,
@@ -1429,8 +1466,11 @@ final class DomainViewModel {
1429 } 1466 }
1430 1467
1431 func loadExtendedSubdomains() async { 1468 func loadExtendedSubdomains() async {
1432 await loadLookup(.extendedSubdomains, into: \.extendedSubdomains, loading: \.extendedSubdomainsLoading, error: \.extendedSubdomainsError, 1469 await loadLookup(
1433 fallback: "Extended subdomains unavailable") { 1470 .extendedSubdomains,
1471 into: \.extendedSubdomainsState,
1472 fallback: "Extended subdomains unavailable"
1473 ) {
1434 await ExternalDataService.shared.extendedSubdomains( 1474 await ExternalDataService.shared.extendedSubdomains(
1435 domain: searchedDomain, 1475 domain: searchedDomain,
1436 existing: subdomains 1476 existing: subdomains
@@ -1443,9 +1483,7 @@ final class DomainViewModel {
1443 /// doesn't include it; without one the lookup is open to every tier. 1483 /// doesn't include it; without one the lookup is open to every tier.
1444 private func loadLookup<Item>( 1484 private func loadLookup<Item>(
1445 _ capability: FeatureCapability? = nil, 1485 _ capability: FeatureCapability? = nil,
1446 into items: ReferenceWritableKeyPath<DomainViewModel, [Item]>, 1486 into state: ReferenceWritableKeyPath<DomainViewModel, SectionState<[Item]>>,
1447 loading: ReferenceWritableKeyPath<DomainViewModel, Bool>,
1448 error: ReferenceWritableKeyPath<DomainViewModel, String?>,
1449 fallback: String, 1487 fallback: String,
1450 fetch: () async -> ServiceResult<[Item]> 1488 fetch: () async -> ServiceResult<[Item]>
1451 ) async { 1489 ) async {
@@ -1454,14 +1492,11 @@ final class DomainViewModel {
1454 upgradePrompt = FeatureAccessService.upgradePrompt(for: capability) 1492 upgradePrompt = FeatureAccessService.upgradePrompt(for: capability)
1455 return 1493 return
1456 } 1494 }
1457 guard self[keyPath: items].isEmpty else { return } 1495 guard self[keyPath: state].items.isEmpty else { return }
1458
1459 self[keyPath: loading] = true
1460 self[keyPath: error] = nil
1461
1462 (self[keyPath: items], self[keyPath: error]) = found(await fetch(), fallback: fallback)
1463 1496
1464 self[keyPath: loading] = false 1497 self[keyPath: state] = .loading
1498 let (items, message) = found(await fetch(), fallback: fallback)
1499 self[keyPath: state] = .settled(value: items, error: message)
1465 _ = saveHistoryEntry(replaceLatest: true) 1500 _ = saveHistoryEntry(replaceLatest: true)
1466 } 1501 }
1467 1502
@@ -1506,7 +1541,10 @@ final class DomainViewModel {
1506 return entry 1541 return entry
1507 } 1542 }
1508 1543
1509 private func applySnapshot(_ snapshot: LookupSnapshot) { 1544 /// The single place section state is written from an inspection result.
1545 /// Internal so the tests that pin what each section ends up showing can
1546 /// reach it without a live lookup.
1547 func applySnapshot(_ snapshot: LookupSnapshot) {
1510 currentHistoryEntryID = snapshot.historyEntryID 1548 currentHistoryEntryID = snapshot.historyEntryID
1511 currentSnapshotTimestamp = snapshot.timestamp 1549 currentSnapshotTimestamp = snapshot.timestamp
1512 currentResultSource = snapshot.resultSource 1550 currentResultSource = snapshot.resultSource
@@ -1527,79 +1565,44 @@ final class DomainViewModel {
1527 DomainDebugLog.signpostEnd("DomainViewModel.reportBuilder.build", start: reportStartedAt, domain: snapshot.domain) 1565 DomainDebugLog.signpostEnd("DomainViewModel.reportBuilder.build", start: reportStartedAt, domain: snapshot.domain)
1528 currentChangeSummary = currentReport?.changeSummary ?? snapshot.changeSummary 1566 currentChangeSummary = currentReport?.changeSummary ?? snapshot.changeSummary
1529 1567
1530 dnsSections = snapshot.dnsSections 1568 dnsState = .settled(value: snapshot.dnsSections, error: snapshot.dnsError)
1531 dnsError = snapshot.dnsError 1569 availabilityState = .settled(value: snapshot.availabilityResult)
1532 availabilityResult = snapshot.availabilityResult 1570 suggestionsState = .settled(value: snapshot.suggestions)
1533 suggestions = snapshot.suggestions 1571 sslState = .settled(value: snapshot.sslInfo, error: snapshot.sslError)
1534 sslInfo = snapshot.sslInfo 1572 hstsState = .settled(value: snapshot.hstsPreloaded)
1535 sslError = snapshot.sslError 1573 httpHeadersState = .settled(value: snapshot.httpHeaders, error: snapshot.httpHeadersError)
1536 hstsPreloaded = snapshot.hstsPreloaded
1537 httpHeaders = snapshot.httpHeaders
1538 httpSecurityGrade = snapshot.httpSecurityGrade 1574 httpSecurityGrade = snapshot.httpSecurityGrade
1539 httpStatusCode = snapshot.httpStatusCode 1575 httpStatusCode = snapshot.httpStatusCode
1540 httpResponseTimeMs = snapshot.httpResponseTimeMs 1576 httpResponseTimeMs = snapshot.httpResponseTimeMs
1541 httpProtocol = snapshot.httpProtocol 1577 httpProtocol = snapshot.httpProtocol
1542 http3Advertised = snapshot.http3Advertised 1578 http3Advertised = snapshot.http3Advertised
1543 httpHeadersError = snapshot.httpHeadersError 1579 reachabilityState = .settled(value: snapshot.reachabilityResults, error: snapshot.reachabilityError)
1544 reachabilityResults = snapshot.reachabilityResults 1580 ipGeolocationState = .settled(value: snapshot.ipGeolocation, error: snapshot.ipGeolocationError)
1545 reachabilityError = snapshot.reachabilityError 1581 emailSecurityState = .settled(value: snapshot.emailSecurity, error: snapshot.emailSecurityError)
1546 ipGeolocation = snapshot.ipGeolocation 1582 ownershipState = .settled(value: snapshot.ownership, error: snapshot.ownershipError)
1547 ipGeolocationError = snapshot.ipGeolocationError 1583 ownershipHistoryState = .settled(value: snapshot.ownershipHistory, error: snapshot.ownershipHistoryError)
1548 emailSecurity = snapshot.emailSecurity 1584 ptrState = .settled(value: snapshot.ptrRecord, error: snapshot.ptrError)
1549 emailSecurityError = snapshot.emailSecurityError 1585 redirectChainState = .settled(value: snapshot.redirectChain, error: snapshot.redirectChainError)
1550 ownershipResult = snapshot.ownership 1586 subdomainsState = .settled(value: snapshot.subdomains, error: snapshot.subdomainsError)
1551 ownershipError = snapshot.ownershipError 1587 extendedSubdomainsState = .settled(value: snapshot.extendedSubdomains, error: snapshot.extendedSubdomainsError)
1552 ownershipHistory = snapshot.ownershipHistory 1588 dnsHistoryState = .settled(value: snapshot.dnsHistory, error: snapshot.dnsHistoryError)
1553 ownershipHistoryError = snapshot.ownershipHistoryError 1589 domainPricingState = .settled(value: snapshot.domainPricing, error: snapshot.domainPricingError)
1554 ptrRecord = snapshot.ptrRecord 1590 reputationState = .settled(value: snapshot.reputation, error: snapshot.reputationError)
1555 ptrError = snapshot.ptrError 1591 portScanState = .settled(
1556 redirectChain = snapshot.redirectChain 1592 value: snapshot.portScanResults.filter { $0.kind == .standard },
1557 redirectChainError = snapshot.redirectChainError 1593 error: snapshot.portScanError
1558 subdomains = snapshot.subdomains 1594 )
1559 subdomainsError = snapshot.subdomainsError 1595 customPortScanState = .settled(value: snapshot.portScanResults.filter { $0.kind == .custom })
1560 extendedSubdomains = snapshot.extendedSubdomains
1561 extendedSubdomainsError = snapshot.extendedSubdomainsError
1562 dnsHistory = snapshot.dnsHistory
1563 dnsHistoryError = snapshot.dnsHistoryError
1564 domainPricing = snapshot.domainPricing
1565 domainPricingError = snapshot.domainPricingError
1566 portScanResults = snapshot.portScanResults.filter { $0.kind == .standard }
1567 customPortResults = snapshot.portScanResults.filter { $0.kind == .custom }
1568 portScanError = snapshot.portScanError
1569 customPortScanError = nil
1570
1571 dnsLoading = false
1572 availabilityLoading = false
1573 suggestionsLoading = false
1574 sslLoading = false
1575 hstsLoading = false
1576 httpHeadersLoading = false
1577 reachabilityLoading = false
1578 ipGeolocationLoading = false
1579 emailSecurityLoading = false
1580 ownershipLoading = false
1581 ownershipHistoryLoading = false
1582 ptrLoading = false
1583 redirectChainLoading = false
1584 subdomainsLoading = false
1585 extendedSubdomainsLoading = false
1586 dnsHistoryLoading = false
1587 domainPricingLoading = false
1588 portScanLoading = false
1589 customPortScanLoading = false
1590 } 1596 }
1591 1597
1592 private func applyCustomPortResult(_ result: ServiceResult<[PortScanResult]>) { 1598 private func applyCustomPortResult(_ result: ServiceResult<[PortScanResult]>) {
1593 switch result { 1599 switch result {
1594 case let .success(results): 1600 case let .success(results):
1595 customPortResults = results 1601 customPortScanState = .settled(value: results)
1596 customPortScanError = nil
1597 _ = saveHistoryEntry(replaceLatest: true) 1602 _ = saveHistoryEntry(replaceLatest: true)
1598 case let .empty(message), let .error(message): 1603 case let .empty(message), let .error(message):
1599 customPortResults = [] 1604 customPortScanState = .settled(value: [], error: message)
1600 customPortScanError = message
1601 } 1605 }
1602 customPortScanLoading = false
1603 } 1606 }
1604 1607
1605 private static func performBatchLookup(domain: String, previousSnapshot: LookupSnapshot?) async -> BatchLookupPayload? { 1608 private static func performBatchLookup(domain: String, previousSnapshot: LookupSnapshot?) async -> BatchLookupPayload? {
@@ -2111,7 +2114,6 @@ final class DomainViewModel {
2111 ownershipDiff = [] 2114 ownershipDiff = []
2112 clearLookupState() 2115 clearLookupState()
2113 setAllLoadingStates(true) 2116 setAllLoadingStates(true)
2114 customPortScanLoading = false
2115 return lookupID 2117 return lookupID
2116 } 2118 }
2117 2119
@@ -2382,93 +2384,62 @@ final class DomainViewModel {
2382 ) 2384 )
2383 } 2385 }
2384 2386
2387 /// Resets every section before a new lookup, so the previous domain's
2388 /// results cannot be mistaken for this one's. One assignment per section
2389 /// now; it used to be three.
2385 private func clearLookupState() { 2390 private func clearLookupState() {
2386 dnsSections = [] 2391 dnsState = .idle
2387 dnsError = nil 2392 availabilityState = .idle
2388 dnsLoading = false 2393 suggestionsState = .idle
2389 availabilityResult = nil 2394 sslState = .idle
2390 availabilityLoading = false 2395 hstsState = .idle
2391 suggestions = [] 2396 httpHeadersState = .idle
2392 suggestionsLoading = false
2393 sslInfo = nil
2394 sslError = nil
2395 sslLoading = false
2396 hstsPreloaded = nil
2397 hstsLoading = false
2398 httpHeaders = []
2399 httpSecurityGrade = nil 2397 httpSecurityGrade = nil
2400 httpStatusCode = nil 2398 httpStatusCode = nil
2401 httpResponseTimeMs = nil 2399 httpResponseTimeMs = nil
2402 httpProtocol = nil 2400 httpProtocol = nil
2403 http3Advertised = false 2401 http3Advertised = false
2404 httpHeadersError = nil 2402 reachabilityState = .idle
2405 httpHeadersLoading = false 2403 ipGeolocationState = .idle
2406 reachabilityResults = [] 2404 emailSecurityState = .idle
2407 reachabilityError = nil 2405 ownershipState = .idle
2408 reachabilityLoading = false 2406 ownershipHistoryState = .idle
2409 ipGeolocation = nil 2407 ptrState = .idle
2410 ipGeolocationError = nil 2408 redirectChainState = .idle
2411 ipGeolocationLoading = false 2409 subdomainsState = .idle
2412 emailSecurity = nil 2410 extendedSubdomainsState = .idle
2413 emailSecurityError = nil 2411 dnsHistoryState = .idle
2414 emailSecurityLoading = false 2412 domainPricingState = .idle
2415 ownershipResult = nil 2413 reputationState = .idle
2416 ownershipError = nil 2414 portScanState = .idle
2417 ownershipLoading = false 2415 customPortScanState = .idle
2418 ownershipHistory = [] 2416 }
2419 ownershipHistoryError = nil 2417
2420 ownershipHistoryLoading = false 2418 /// Puts the sections a lookup drives into flight, and resets the
2421 ptrRecord = nil 2419 /// on-demand ones — ownership history, extended subdomains, DNS history
2422 ptrError = nil 2420 /// and pricing are fetched when the user opens them, not by the lookup, so
2423 ptrLoading = false 2421 /// they were never part of this either.
2424 redirectChain = []
2425 redirectChainError = nil
2426 redirectChainLoading = false
2427 subdomains = []
2428 subdomainsError = nil
2429 subdomainsLoading = false
2430 extendedSubdomains = []
2431 extendedSubdomainsError = nil
2432 extendedSubdomainsLoading = false
2433 dnsHistory = []
2434 dnsHistoryError = nil
2435 dnsHistoryLoading = false
2436 domainPricing = nil
2437 domainPricingError = nil
2438 domainPricingLoading = false
2439 portScanResults = []
2440 portScanError = nil
2441 portScanLoading = false
2442 customPortResults = []
2443 customPortScanError = nil
2444 customPortScanLoading = false
2445 currentHistoryEntryID = nil
2446 currentSnapshotTimestamp = Date()
2447 currentResultSource = .live
2448 currentCachedSections = []
2449 currentStatusMessage = nil
2450 currentReport = nil
2451 }
2452
2453 private func setAllLoadingStates(_ loading: Bool) { 2422 private func setAllLoadingStates(_ loading: Bool) {
2454 dnsLoading = loading 2423 let phase: SectionPhase = loading ? .loading : .idle
2455 availabilityLoading = loading 2424 dnsState.phase = phase
2456 suggestionsLoading = loading 2425 availabilityState.phase = phase
2457 sslLoading = loading 2426 suggestionsState.phase = phase
2458 hstsLoading = loading 2427 sslState.phase = phase
2459 httpHeadersLoading = loading 2428 hstsState.phase = phase
2460 reachabilityLoading = loading 2429 httpHeadersState.phase = phase
2461 ipGeolocationLoading = loading 2430 reachabilityState.phase = phase
2462 emailSecurityLoading = loading 2431 ipGeolocationState.phase = phase
2463 ownershipLoading = loading 2432 emailSecurityState.phase = phase
2464 ownershipHistoryLoading = false 2433 ownershipState.phase = phase
2465 ptrLoading = loading 2434 ptrState.phase = phase
2466 redirectChainLoading = loading 2435 redirectChainState.phase = phase
2467 subdomainsLoading = loading 2436 subdomainsState.phase = phase
2468 extendedSubdomainsLoading = false 2437 portScanState.phase = phase
2469 dnsHistoryLoading = false 2438
2470 domainPricingLoading = false 2439 ownershipHistoryState.phase = .idle
2471 portScanLoading = loading 2440 extendedSubdomainsState.phase = .idle
2441 dnsHistoryState.phase = .idle
2442 domainPricingState.phase = .idle
2472 } 2443 }
2473 2444
2474 private func primaryIPAddress(from sections: [DNSSection]) -> String? { 2445 private func primaryIPAddress(from sections: [DNSSection]) -> String? {
DomainDig/SectionState.swift added +56
@@ -0,0 +1,56 @@
1import Foundation
2
3/// One inspection section's state as a single value.
4///
5/// Each section used to be three independent stored properties — a value, a
6/// `*Loading` flag and a `*Error` string. There were 20 flags and 19 error
7/// strings (A2), and nothing tied each trio together: a section could be left
8/// loading forever because one of three assignments was missed, or report an
9/// error while still claiming to load.
10///
11/// Deliberately **not** an exclusive `loaded | failed` enum, which is what A2
12/// proposed. A section really can have both: the TLS card renders a stale
13/// certificate next to a handshake error, and `AppStatusFactory.tls` takes
14/// `sslInfo` and `error` together. An enum would have to drop one of them.
15/// `SectionStateTests.testAnErrorAndAValueTogetherKeepBothReachable` pins that.
16///
17/// Whether a section is still moving. Declared outside `SectionState` so one
18/// value can be applied across sections holding different value types.
19enum SectionPhase {
20 /// Not started, or cleared because a new lookup began.
21 case idle
22 /// In flight.
23 case loading
24 /// Finished, with a value, an error, or both.
25 case settled
26}
27
28/// One inspection section's state as a single value: see `SectionPhase` above
29/// for the phases. What this fixes is that the value, the phase and the error
30/// travel together, so they are written as one or not at all.
31struct SectionState<Value> {
32 var phase: SectionPhase = .idle
33 var value: Value?
34 var error: String?
35
36 var isLoading: Bool { phase == .loading }
37
38 /// Finished moving, either way. `resultsLoaded` used to ask fifteen
39 /// separate loading flags this question.
40 var isSettled: Bool { phase == .settled }
41
42 static var idle: Self { Self() }
43 static var loading: Self { Self(phase: .loading) }
44
45 /// Finished with whatever the lookup produced. Both arguments are optional
46 /// because a snapshot carries them independently.
47 static func settled(value: Value?, error: String? = nil) -> Self {
48 Self(phase: .settled, value: value, error: error)
49 }
50}
51
52extension SectionState where Value: ExpressibleByArrayLiteral {
53 /// The value, or an empty collection — what the row builders want, rather
54 /// than an optional they would immediately coalesce.
55 var items: Value { value ?? [] }
56}
DomainDigTests/Fixtures/SnapshotFixture.swift +47 −13
@@ -17,6 +17,25 @@ enum SnapshotFixture {
17 17
18 static let defaultResolverURL = "https://resolver.example/dns-query" 18 static let defaultResolverURL = "https://resolver.example/dns-query"
19 19
20 /// Per-section failure messages, so a test can build a snapshot where one
21 /// section failed and the rest succeeded. `LookupSnapshot` keeps a value
22 /// and an error per section independently, and the views render the error
23 /// over the value — which is the contract the section slices have to
24 /// preserve.
25 struct SectionFailures {
26 var dnsError: String?
27 var sslError: String?
28 var httpHeadersError: String?
29 var reachabilityError: String?
30 var ipGeolocationError: String?
31 var emailSecurityError: String?
32 var ownershipError: String?
33 var ptrError: String?
34 var redirectChainError: String?
35 var subdomainsError: String?
36 var portScanError: String?
37 }
38
20 static func snapshot( 39 static func snapshot(
21 domain: String = "example.com", 40 domain: String = "example.com",
22 timestamp: Date = referenceDate, 41 timestamp: Date = referenceDate,
@@ -34,7 +53,9 @@ enum SnapshotFixture {
34 extendedSubdomains: [DiscoveredSubdomain] = [], 53 extendedSubdomains: [DiscoveredSubdomain] = [],
35 isPartialSnapshot: Bool = false, 54 isPartialSnapshot: Bool = false,
36 validationIssues: [String] = [], 55 validationIssues: [String] = [],
37 changeSummary: DomainChangeSummary? = nil 56 changeSummary: DomainChangeSummary? = nil,
57 failures: SectionFailures = SectionFailures(),
58 provenanceBySection: [LookupSectionKind: SectionProvenance] = [:]
38 ) -> LookupSnapshot { 59 ) -> LookupSnapshot {
39 LookupSnapshot( 60 LookupSnapshot(
40 historyEntryID: nil, 61 historyEntryID: nil,
@@ -46,7 +67,7 @@ enum SnapshotFixture {
46 resolverDisplayName: "Test Resolver", 67 resolverDisplayName: "Test Resolver",
47 resolverURLString: resolverURLString, 68 resolverURLString: resolverURLString,
48 dataSources: [], 69 dataSources: [],
49 provenanceBySection: [:], 70 provenanceBySection: provenanceBySection,
50 availabilityConfidence: nil, 71 availabilityConfidence: nil,
51 ownershipConfidence: nil, 72 ownershipConfidence: nil,
52 subdomainConfidence: nil, 73 subdomainConfidence: nil,
@@ -61,11 +82,11 @@ enum SnapshotFixture {
61 changeCount: 0, 82 changeCount: 0,
62 severitySummary: nil, 83 severitySummary: nil,
63 dnsSections: dnsSections, 84 dnsSections: dnsSections,
64 dnsError: nil, 85 dnsError: failures.dnsError,
65 availabilityResult: availability.map { DomainAvailabilityResult(domain: domain, status: $0) }, 86 availabilityResult: availability.map { DomainAvailabilityResult(domain: domain, status: $0) },
66 suggestions: [], 87 suggestions: [],
67 sslInfo: sslInfo, 88 sslInfo: sslInfo,
68 sslError: nil, 89 sslError: failures.sslError,
69 hstsPreloaded: nil, 90 hstsPreloaded: nil,
70 httpHeaders: httpHeaders, 91 httpHeaders: httpHeaders,
71 httpSecurityGrade: httpSecurityGrade, 92 httpSecurityGrade: httpSecurityGrade,
@@ -73,15 +94,15 @@ enum SnapshotFixture {
73 httpResponseTimeMs: nil, 94 httpResponseTimeMs: nil,
74 httpProtocol: nil, 95 httpProtocol: nil,
75 http3Advertised: false, 96 http3Advertised: false,
76 httpHeadersError: nil, 97 httpHeadersError: failures.httpHeadersError,
77 reachabilityResults: [], 98 reachabilityResults: [],
78 reachabilityError: nil, 99 reachabilityError: failures.reachabilityError,
79 ipGeolocation: nil, 100 ipGeolocation: nil,
80 ipGeolocationError: nil, 101 ipGeolocationError: failures.ipGeolocationError,
81 emailSecurity: nil, 102 emailSecurity: nil,
82 emailSecurityError: nil, 103 emailSecurityError: failures.emailSecurityError,
83 ownership: ownership, 104 ownership: ownership,
84 ownershipError: nil, 105 ownershipError: failures.ownershipError,
85 ownershipHistory: [], 106 ownershipHistory: [],
86 ownershipHistoryError: nil, 107 ownershipHistoryError: nil,
87 inferredProvider: nil, 108 inferredProvider: nil,
@@ -93,11 +114,11 @@ enum SnapshotFixture {
93 riskSignals: [], 114 riskSignals: [],
94 intelligenceTimeline: [], 115 intelligenceTimeline: [],
95 ptrRecord: ptrRecord, 116 ptrRecord: ptrRecord,
96 ptrError: nil, 117 ptrError: failures.ptrError,
97 redirectChain: [], 118 redirectChain: [],
98 redirectChainError: nil, 119 redirectChainError: failures.redirectChainError,
99 subdomains: subdomains, 120 subdomains: subdomains,
100 subdomainsError: nil, 121 subdomainsError: failures.subdomainsError,
101 extendedSubdomains: extendedSubdomains, 122 extendedSubdomains: extendedSubdomains,
102 extendedSubdomainsError: nil, 123 extendedSubdomainsError: nil,
103 dnsHistory: [], 124 dnsHistory: [],
@@ -107,7 +128,7 @@ enum SnapshotFixture {
107 reputation: nil, 128 reputation: nil,
108 reputationError: nil, 129 reputationError: nil,
109 portScanResults: [], 130 portScanResults: [],
110 portScanError: nil, 131 portScanError: failures.portScanError,
111 changeSummary: changeSummary, 132 changeSummary: changeSummary,
112 resultSource: resultSource, 133 resultSource: resultSource,
113 cachedSections: [], 134 cachedSections: [],
@@ -249,6 +270,19 @@ enum SnapshotFixture {
249 ) 270 )
250 } 271 }
251 272
273 static func provenance(
274 source: String = "test",
275 resultSource: LookupResultSource = .live
276 ) -> SectionProvenance {
277 SectionProvenance(
278 source: source,
279 collectedAt: referenceDate,
280 provider: nil,
281 resolver: nil,
282 resultSource: resultSource
283 )
284 }
285
252 static func certificate( 286 static func certificate(
253 commonName: String = "example.com", 287 commonName: String = "example.com",
254 issuer: String = "Test CA", 288 issuer: String = "Test CA",
DomainDigTests/SectionStateTests.swift added +243
@@ -0,0 +1,243 @@
1import XCTest
2@testable import DomainDig
3
4/// What each result section ends up showing after an inspection lands.
5///
6/// `applySnapshot` is the one place section state is written, and until now
7/// nothing covered it — which is why A2's collapse of the 20 `*Loading` flags
8/// and 19 `*Error` strings into `SectionState` could not be attempted safely.
9/// These assert on the section slices the views actually consume rather than
10/// on the raw properties behind them, so they survive that collapse and are
11/// the thing it must not change.
12@MainActor
13final class SectionStateTests: XCTestCase {
14
15 private var suiteName = ""
16 private var scratch = UserDefaults.standard
17 private var historyLocation = HistoryFileStore.Location.default
18
19 override func setUpWithError() throws {
20 try super.setUpWithError()
21 suiteName = "net.cleberg.DomainDig.tests.\(UUID().uuidString)"
22 scratch = try XCTUnwrap(UserDefaults(suiteName: suiteName))
23 historyLocation = HistoryFileStore.Location(
24 root: URL(fileURLWithPath: NSTemporaryDirectory())
25 .appendingPathComponent("DomainDigSectionTest-\(UUID().uuidString)", isDirectory: true)
26 )
27 }
28
29 override func tearDown() {
30 UserDefaults.standard.removePersistentDomain(forName: suiteName)
31 HistoryFileStore.removeAll(at: historyLocation)
32 super.tearDown()
33 }
34
35 /// Releasing a main-actor-isolated object aborts the runner on iOS 18.6
36 /// (E1), and `Scripts/test.sh` runs that tier.
37 private static var retained: [DomainViewModel] = []
38
39 private func makeViewModel() -> DomainViewModel {
40 let viewModel = DomainViewModel(defaults: scratch, historyLocation: historyLocation)
41 Self.retained.append(viewModel)
42 return viewModel
43 }
44
45 // MARK: Loading
46
47 /// Starting a lookup puts every section in flight; applying a snapshot
48 /// takes them all out of it. Nothing may be left loading, or the section
49 /// spins forever.
50 func testApplyingASnapshotSettlesEverySection() {
51 let viewModel = makeViewModel()
52 _ = viewModel.beginLookup(for: "example.com")
53
54 XCTAssertFalse(viewModel.resultsLoaded, "sections should be in flight after a lookup starts")
55
56 viewModel.applySnapshot(SnapshotFixture.snapshot())
57
58 XCTAssertTrue(viewModel.resultsLoaded, "a section was left loading")
59 XCTAssertFalse(viewModel.webSectionData.tls.isLoading)
60 XCTAssertFalse(viewModel.webSectionData.http.isLoading)
61 XCTAssertFalse(viewModel.webSectionData.redirect.isLoading)
62 XCTAssertFalse(viewModel.networkSectionData.reachability.isLoading)
63 XCTAssertFalse(viewModel.networkSectionData.location.isLoading)
64 XCTAssertFalse(viewModel.networkSectionData.portScan.isLoading)
65 XCTAssertFalse(viewModel.networkSectionData.customPortScan.isLoading)
66 }
67
68 /// `resultsLoaded` gates the whole results area, so it must not read true
69 /// before a lookup has ever run.
70 func testResultsAreNotLoadedBeforeAnyLookup() {
71 XCTAssertFalse(makeViewModel().resultsLoaded)
72 }
73
74 // MARK: Values
75
76 func testASuccessfulSnapshotPopulatesTheWebSection() throws {
77 let viewModel = makeViewModel()
78 let certificate = SnapshotFixture.certificate(commonName: "example.com", issuer: "Test CA")
79
80 viewModel.applySnapshot(
81 SnapshotFixture.snapshot(
82 sslInfo: certificate,
83 httpHeaders: [HTTPHeader(name: "server", value: "test")]
84 )
85 )
86
87 let web = viewModel.webSectionData
88 XCTAssertNil(web.tls.error)
89 XCTAssertEqual(web.sslInfo?.commonName, "example.com")
90 XCTAssertEqual(web.sslInfo?.issuer, "Test CA")
91 XCTAssertNil(web.http.error)
92 XCTAssertEqual(web.headers.map(\.name), ["server"])
93 }
94
95 func testASuccessfulSnapshotPopulatesTheNetworkSection() {
96 let viewModel = makeViewModel()
97
98 viewModel.applySnapshot(SnapshotFixture.snapshot(dnsSections: [
99 SnapshotFixture.dnsSection(type: .A, values: ["203.0.113.1"])
100 ]))
101
102 let network = viewModel.networkSectionData
103 XCTAssertNil(network.reachability.error)
104 XCTAssertNil(network.location.error)
105 XCTAssertNil(network.portScan.error)
106 }
107
108 func testTheDNSSectionTakesItsRecordsFromTheSnapshot() {
109 let viewModel = makeViewModel()
110
111 viewModel.applySnapshot(SnapshotFixture.snapshot(dnsSections: [
112 SnapshotFixture.dnsSection(type: .A, values: ["203.0.113.1", "203.0.113.2"]),
113 SnapshotFixture.dnsSection(type: .MX, values: ["10 mail.example.com"])
114 ]))
115
116 XCTAssertEqual(viewModel.dnsSections.map(\.recordType), [.A, .MX])
117 XCTAssertEqual(
118 viewModel.dnsSections.flatMap { $0.records.map(\.value) },
119 ["203.0.113.1", "203.0.113.2", "10 mail.example.com"]
120 )
121 XCTAssertNil(viewModel.dnsError)
122 }
123
124 // MARK: Failures
125
126 func testAFailedSectionCarriesItsMessage() {
127 let viewModel = makeViewModel()
128
129 viewModel.applySnapshot(
130 SnapshotFixture.snapshot(
131 failures: .init(sslError: "handshake failed", httpHeadersError: "timed out")
132 )
133 )
134
135 XCTAssertEqual(viewModel.webSectionData.tls.error, "handshake failed")
136 XCTAssertEqual(viewModel.webSectionData.http.error, "timed out")
137 }
138
139 /// One section failing must not mark the others failed. Partial snapshots
140 /// are the normal case, not the exception.
141 func testOneFailedSectionLeavesTheOthersAlone() {
142 let viewModel = makeViewModel()
143
144 viewModel.applySnapshot(SnapshotFixture.snapshot(failures: .init(sslError: "handshake failed")))
145
146 XCTAssertEqual(viewModel.webSectionData.tls.error, "handshake failed")
147 XCTAssertNil(viewModel.webSectionData.http.error)
148 XCTAssertNil(viewModel.webSectionData.redirect.error)
149 XCTAssertNil(viewModel.networkSectionData.reachability.error)
150 XCTAssertNil(viewModel.networkSectionData.location.error)
151 XCTAssertNil(viewModel.networkSectionData.portScan.error)
152 }
153
154 func testEachNetworkCardCarriesItsOwnFailure() {
155 let viewModel = makeViewModel()
156
157 viewModel.applySnapshot(
158 SnapshotFixture.snapshot(
159 failures: .init(
160 reachabilityError: "no route",
161 ipGeolocationError: "no geolocation",
162 portScanError: "scan refused"
163 )
164 )
165 )
166
167 let network = viewModel.networkSectionData
168 XCTAssertEqual(network.reachability.error, "no route")
169 XCTAssertEqual(network.location.error, "no geolocation")
170 XCTAssertEqual(network.portScan.error, "scan refused")
171 }
172
173 /// A snapshot can carry a value *and* an error for one section, and every
174 /// section view renders `loading → error → rows`: the error wins and the
175 /// value is not shown. Collapsing the triples must keep that order, and
176 /// must keep the value reachable where a card reads it alongside the error
177 /// — the TLS badge takes both.
178 func testAnErrorAndAValueTogetherKeepBothReachable() {
179 let viewModel = makeViewModel()
180
181 viewModel.applySnapshot(
182 SnapshotFixture.snapshot(
183 sslInfo: SnapshotFixture.certificate(commonName: "stale.example"),
184 failures: .init(sslError: "handshake failed")
185 )
186 )
187
188 let web = viewModel.webSectionData
189 XCTAssertEqual(web.tls.error, "handshake failed", "the error must still be what the card shows")
190 XCTAssertEqual(
191 web.sslInfo?.commonName, "stale.example",
192 "the TLS badge reads sslInfo alongside the error, so it must survive"
193 )
194 }
195
196 // MARK: Provenance
197
198 /// Provenance does not come from the snapshot that was just applied.
199 /// `currentSnapshot` reads it from the saved history entry
200 /// (`DomainViewModel:623`), and `applySnapshot` stores it nowhere — so
201 /// between applying and saving, and on a lookup that ends with a status
202 /// message and is therefore never saved, the cards show no provenance at
203 /// all. Recorded as A12.
204 ///
205 /// This pins the behaviour as it is rather than as it should be, so that
206 /// A2's collapse can carry provenance with the section state and change
207 /// this test deliberately.
208 func testProvenanceIsNotCarriedByTheAppliedSnapshot() {
209 let viewModel = makeViewModel()
210
211 viewModel.applySnapshot(
212 SnapshotFixture.snapshot(
213 provenanceBySection: [.ssl: SnapshotFixture.provenance(source: "test")]
214 )
215 )
216
217 XCTAssertNil(
218 viewModel.webSectionData.tls.provenance,
219 "provenance now survives applySnapshot — update this test and close A12"
220 )
221 }
222
223 // MARK: A second lookup clears the first one's results
224
225 /// Starting a new lookup must not leave the previous domain's sections on
226 /// screen as though they belonged to the new one.
227 func testANewLookupClearsThePreviousSectionResults() {
228 let viewModel = makeViewModel()
229 viewModel.applySnapshot(
230 SnapshotFixture.snapshot(
231 domain: "first.example",
232 dnsSections: [SnapshotFixture.dnsSection(type: .A, values: ["203.0.113.1"])],
233 failures: .init(sslError: "handshake failed")
234 )
235 )
236 XCTAssertFalse(viewModel.dnsSections.isEmpty)
237
238 _ = viewModel.beginLookup(for: "second.example")
239
240 XCTAssertTrue(viewModel.dnsSections.isEmpty, "the previous domain's records survived a new lookup")
241 XCTAssertNil(viewModel.webSectionData.tls.error, "the previous domain's failure survived a new lookup")
242 }
243}