Commit 23128a2989

23128a29894027174cf7343e02a432c7ee6111d7

parent: 4294e59fca

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-23 01:19 UTC

Split inspection, monitoring and view code; share repeated UI

- inspectSnapshot records sections in an InspectionLedger instead of
  threading four inout accumulators through 14 calls; reuse-or-fetch and
  routable-only lookups are helpers.
- Monitoring alert delivery, the SMTP connection's start outcome, and the
  watchlist row's buttons are their own functions.
- ResultSectionViews' nested blocks are named properties.
- Export menus, batch result sections, dashboard domain links, quiet-hour
  pickers, sync last-writer-wins merges and keychain access are shared.

Layout: unified · split

DomainDig/BatchSweepSummaryView.swift +37 −19
@@ -28,25 +28,12 @@ struct BatchSweepSummaryView: View {
28 Toggle("Show unchanged domains", isOn: $showUnchangedDomains) 28 Toggle("Show unchanged domains", isOn: $showUnchangedDomains)
29 } 29 }
30 30
31 Section(visibleResults.isEmpty ? "Changed Domains" : "Results") { 31 BatchResultsSection(
32 if visibleResults.isEmpty { 32 viewModel: viewModel,
33 Text("No domains with changes or warnings") 33 results: visibleResults,
34 .font(.system(.caption, design: .monospaced)) 34 emptyTitle: "Changed Domains",
35 .foregroundStyle(Color(.appTextSecondary)) 35 emptyText: "No domains with changes or warnings"
36 } else { 36 )
37 ForEach(visibleResults) { result in
38 if let entry = viewModel.historyEntry(for: result) {
39 NavigationLink {
40 HistoryDetailView(viewModel: viewModel, entry: entry)
41 } label: {
42 BatchResultRowView(result: result)
43 }
44 } else {
45 BatchResultRowView(result: result)
46 }
47 }
48 }
49 }
50 } 37 }
51 .navigationTitle(summary.source == .watchlistRefresh ? "Sweep Summary" : "Batch Summary") 38 .navigationTitle(summary.source == .watchlistRefresh ? "Sweep Summary" : "Batch Summary")
52 } 39 }
@@ -64,3 +51,34 @@ struct BatchSweepSummaryView: View {
64 } 51 }
65 } 52 }
66} 53}
54
55/// A batch's results, each opening its history entry where one was saved.
56/// Titled `emptyTitle`, with `emptyText` under it, when nothing is shown.
57struct BatchResultsSection: View {
58 @Bindable var viewModel: DomainViewModel
59 let results: [BatchLookupResult]
60 let emptyTitle: String
61 let emptyText: String
62
63 var body: some View {
64 Section(results.isEmpty ? emptyTitle : "Results") {
65 if results.isEmpty {
66 Text(emptyText)
67 .font(.system(.caption, design: .monospaced))
68 .foregroundStyle(Color(.appTextSecondary))
69 } else {
70 ForEach(results) { result in
71 if let entry = viewModel.historyEntry(for: result) {
72 NavigationLink {
73 HistoryDetailView(viewModel: viewModel, entry: entry)
74 } label: {
75 BatchResultRowView(result: result)
76 }
77 } else {
78 BatchResultRowView(result: result)
79 }
80 }
81 }
82 }
83 }
84}
DomainDig/CloudSyncService.swift +17 −17
@@ -782,34 +782,34 @@ final class CloudSyncService {
782 _ lhs: [String: SyncedDomainNote], 782 _ lhs: [String: SyncedDomainNote],
783 _ rhs: [String: SyncedDomainNote] 783 _ rhs: [String: SyncedDomainNote]
784 ) -> (notesByDomain: [String: SyncedDomainNote], hadConflict: Bool) { 784 ) -> (notesByDomain: [String: SyncedDomainNote], hadConflict: Bool) {
785 var merged = lhs 785 let result = mergeLatest(lhs, rhs, updatedAt: \.updatedAt)
786 var hadConflict = false 786 return (result.merged, result.hadConflict)
787
788 for (domain, remoteNote) in rhs {
789 if let localNote = merged[domain], localNote != remoteNote {
790 hadConflict = true
791 merged[domain] = localNote.updatedAt >= remoteNote.updatedAt ? localNote : remoteNote
792 } else {
793 merged[domain] = remoteNote
794 }
795 }
796
797 return (merged, hadConflict)
798 } 787 }
799 788
800 private func mergeHistoryMetadata( 789 private func mergeHistoryMetadata(
801 _ lhs: [String: SyncedHistoryMetadata], 790 _ lhs: [String: SyncedHistoryMetadata],
802 _ rhs: [String: SyncedHistoryMetadata] 791 _ rhs: [String: SyncedHistoryMetadata]
803 ) -> (historyMetadataByDomain: [String: SyncedHistoryMetadata], hadConflict: Bool) { 792 ) -> (historyMetadataByDomain: [String: SyncedHistoryMetadata], hadConflict: Bool) {
793 let result = mergeLatest(lhs, rhs, updatedAt: \.updatedAt)
794 return (result.merged, result.hadConflict)
795 }
796
797 /// `rhs` merged over `lhs` by domain; where both differ, the newer wins
798 /// (the local one on a tie) and the merge reports a conflict.
799 private func mergeLatest<Value: Equatable>(
800 _ lhs: [String: Value],
801 _ rhs: [String: Value],
802 updatedAt: KeyPath<Value, Date>
803 ) -> (merged: [String: Value], hadConflict: Bool) {
804 var merged = lhs 804 var merged = lhs
805 var hadConflict = false 805 var hadConflict = false
806 806
807 for (domain, remoteMetadata) in rhs { 807 for (domain, remote) in rhs {
808 if let localMetadata = merged[domain], localMetadata != remoteMetadata { 808 if let local = merged[domain], local != remote {
809 hadConflict = true 809 hadConflict = true
810 merged[domain] = localMetadata.updatedAt >= remoteMetadata.updatedAt ? localMetadata : remoteMetadata 810 merged[domain] = local[keyPath: updatedAt] >= remote[keyPath: updatedAt] ? local : remote
811 } else { 811 } else {
812 merged[domain] = remoteMetadata 812 merged[domain] = remote
813 } 813 }
814 } 814 }
815 815
DomainDig/ContentView.swift +2 −52
@@ -566,32 +566,7 @@ struct ContentView: View {
566 .accessibilityValue(viewModel.isCurrentDomainSaved ? "Saved" : "Not saved") 566 .accessibilityValue(viewModel.isCurrentDomainSaved ? "Saved" : "Not saved")
567 .accessibilityAddTraits(viewModel.isCurrentDomainSaved ? .isSelected : []) 567 .accessibilityAddTraits(viewModel.isCurrentDomainSaved ? .isSelected : [])
568 Menu { 568 Menu {
569 Button("Export TXT") { 569 ExportFormatButtons(share: shareSingleResults)
570 shareSingleResults(format: .text)
571 }
572 if FeatureAccessService.hasAccess(to: .advancedExports) {
573 Button("Export CSV") {
574 shareSingleResults(format: .csv)
575 }
576 Button("Export JSON") {
577 shareSingleResults(format: .json)
578 }
579 Button("Export Markdown") {
580 shareSingleResults(format: .markdown)
581 }
582 Button("Export PDF") {
583 shareSingleResults(format: .pdf)
584 }
585 } else {
586 Button("CSV Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
587 .disabled(true)
588 Button("JSON Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
589 .disabled(true)
590 Button("Markdown Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
591 .disabled(true)
592 Button("PDF Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
593 .disabled(true)
594 }
595 } label: { 570 } label: {
596 Image(systemName: "square.and.arrow.up") 571 Image(systemName: "square.and.arrow.up")
597 .font(appDensity.font(.body, design: .default)) 572 .font(appDensity.font(.body, design: .default))
@@ -619,32 +594,7 @@ struct ContentView: View {
619 showingBatchWorkflowSheet = true 594 showingBatchWorkflowSheet = true
620 } 595 }
621 Divider() 596 Divider()
622 Button("Export Batch TXT") { 597 ExportFormatButtons(share: shareBatchResults, batch: true)
623 shareBatchResults(format: .text)
624 }
625 if FeatureAccessService.hasAccess(to: .advancedExports) {
626 Button("Export Batch CSV") {
627 shareBatchResults(format: .csv)
628 }
629 Button("Export Batch JSON") {
630 shareBatchResults(format: .json)
631 }
632 Button("Export Batch Markdown") {
633 shareBatchResults(format: .markdown)
634 }
635 Button("Export Batch PDF") {
636 shareBatchResults(format: .pdf)
637 }
638 } else {
639 Button("Batch CSV • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
640 .disabled(true)
641 Button("Batch JSON • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
642 .disabled(true)
643 Button("Batch Markdown • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
644 .disabled(true)
645 Button("Batch PDF • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
646 .disabled(true)
647 }
648 } label: { 598 } label: {
649 Label("Export", systemImage: "square.and.arrow.up") 599 Label("Export", systemImage: "square.and.arrow.up")
650 .font(appDensity.font(.caption)) 600 .font(appDensity.font(.caption))
DomainDig/DashboardView.swift +17 −14
@@ -84,13 +84,8 @@ struct DashboardView: View {
84 dashboardEmptyRow("No recent portfolio changes") 84 dashboardEmptyRow("No recent portfolio changes")
85 } else { 85 } else {
86 ForEach(viewModel.filteredPortfolioRecentActivity.prefix(8)) { item in 86 ForEach(viewModel.filteredPortfolioRecentActivity.prefix(8)) { item in
87 if let trackedDomain = viewModel.trackedDomain(withID: item.trackedDomainID) { 87 trackedDomainLink(item.trackedDomainID) {
88 NavigationLink { 88 PortfolioActivityRow(item: item)
89 TrackedDomainDetailView(viewModel: viewModel, trackedDomain: trackedDomain)
90 } label: {
91 PortfolioActivityRow(item: item)
92 }
93 .buttonStyle(.plain)
94 } 89 }
95 } 90 }
96 } 91 }
@@ -102,13 +97,8 @@ struct DashboardView: View {
102 dashboardEmptyRow("Nothing urgent right now") 97 dashboardEmptyRow("Nothing urgent right now")
103 } else { 98 } else {
104 ForEach(viewModel.filteredPortfolioAttentionRequired.prefix(8)) { item in 99 ForEach(viewModel.filteredPortfolioAttentionRequired.prefix(8)) { item in
105 if let trackedDomain = viewModel.trackedDomain(withID: item.trackedDomainID) { 100 trackedDomainLink(item.trackedDomainID) {
106 NavigationLink { 101 PortfolioAttentionRow(item: item)
107 TrackedDomainDetailView(viewModel: viewModel, trackedDomain: trackedDomain)
108 } label: {
109 PortfolioAttentionRow(item: item)
110 }
111 .buttonStyle(.plain)
112 } 102 }
113 } 103 }
114 } 104 }
@@ -271,6 +261,19 @@ struct DashboardView: View {
271 return AnyShapeStyle(Color(.appSurfaceElevated)) 261 return AnyShapeStyle(Color(.appSurfaceElevated))
272 } 262 }
273 263
264 /// `label`, opening the tracked domain's detail; nothing for a domain no longer tracked.
265 @ViewBuilder
266 private func trackedDomainLink<Label: View>(_ id: UUID, @ViewBuilder label: () -> Label) -> some View {
267 if let trackedDomain = viewModel.trackedDomain(withID: id) {
268 NavigationLink {
269 TrackedDomainDetailView(viewModel: viewModel, trackedDomain: trackedDomain)
270 } label: {
271 label()
272 }
273 .buttonStyle(.plain)
274 }
275 }
276
274 private func dashboardEmptyRow(_ message: String) -> some View { 277 private func dashboardEmptyRow(_ message: String) -> some View {
275 Text(message) 278 Text(message)
276 .font(appDensity.font(.caption)) 279 .font(appDensity.font(.caption))
DomainDig/DomainMonitoringService.swift +45 −31
@@ -602,38 +602,13 @@ final class DomainMonitoringService {
602 602
603 if settings.alertsEnabled, 603 if settings.alertsEnabled,
604 alertDescriptor.severity >= settings.alertFilter.minimumSeverity { 604 alertDescriptor.severity >= settings.alertFilter.minimumSeverity {
605 let pendingAlert = MonitoringPendingAlert( 605 alertsTriggered += await raiseAlert(
606 detectedAt: now, 606 alertDescriptor,
607 message: alertDescriptor.message, 607 for: &updated,
608 severity: alertDescriptor.severity, 608 state: &state,
609 changeHash: alertDescriptor.changeHash 609 deferred: isQuiet || !notificationsAuthorized,
610 now: now
610 ) 611 )
611
612 if isQuiet || !notificationsAuthorized {
613 updated.pendingMonitoringAlerts = deduplicatedPendingAlerts(
614 updated.pendingMonitoringAlerts + [pendingAlert]
615 )
616 } else {
617 let pendingAlerts = deduplicatedPendingAlerts(
618 updated.pendingMonitoringAlerts + [pendingAlert]
619 )
620 if pendingAlerts.count > 1 {
621 await LocalNotificationService.shared.notifyMonitoringSummary(
622 domain: trackedDomain.domain,
623 alerts: pendingAlerts
624 )
625 } else {
626 await LocalNotificationService.shared.notifyMonitoringAlert(
627 domain: trackedDomain.domain,
628 message: alertDescriptor.message,
629 severity: alertDescriptor.severity
630 )
631 }
632 alertsTriggered += 1
633 updated.pendingMonitoringAlerts = []
634 updated.lastAlertAt = now
635 state.lastAlertDate = now
636 }
637 } 612 }
638 } 613 }
639 } else { 614 } else {
@@ -668,6 +643,45 @@ final class DomainMonitoringService {
668 return (updated, alertsTriggered) 643 return (updated, alertsTriggered)
669 } 644 }
670 645
646 /// Queues the alert while notifications are deferred; otherwise notifies, folding in
647 /// any queued alerts, and returns the number of notifications sent.
648 private func raiseAlert(
649 _ alertDescriptor: MonitoringAlertDescriptor,
650 for updated: inout TrackedDomain,
651 state: inout MonitoringState,
652 deferred: Bool,
653 now: Date
654 ) async -> Int {
655 let pendingAlert = MonitoringPendingAlert(
656 detectedAt: now,
657 message: alertDescriptor.message,
658 severity: alertDescriptor.severity,
659 changeHash: alertDescriptor.changeHash
660 )
661 let pendingAlerts = deduplicatedPendingAlerts(updated.pendingMonitoringAlerts + [pendingAlert])
662 if deferred {
663 updated.pendingMonitoringAlerts = pendingAlerts
664 return 0
665 }
666
667 if pendingAlerts.count > 1 {
668 await LocalNotificationService.shared.notifyMonitoringSummary(
669 domain: updated.domain,
670 alerts: pendingAlerts
671 )
672 } else {
673 await LocalNotificationService.shared.notifyMonitoringAlert(
674 domain: updated.domain,
675 message: alertDescriptor.message,
676 severity: alertDescriptor.severity
677 )
678 }
679 updated.pendingMonitoringAlerts = []
680 updated.lastAlertAt = now
681 state.lastAlertDate = now
682 return 1
683 }
684
671 private func deduplicatedPendingAlerts(_ alerts: [MonitoringPendingAlert]) -> [MonitoringPendingAlert] { 685 private func deduplicatedPendingAlerts(_ alerts: [MonitoringPendingAlert]) -> [MonitoringPendingAlert] {
672 var uniqueByHash: [String: MonitoringPendingAlert] = [:] 686 var uniqueByHash: [String: MonitoringPendingAlert] = [:]
673 for alert in alerts { 687 for alert in alerts {
DomainDig/ExportPresenter.swift +32
@@ -30,3 +30,35 @@ enum ExportPresenter {
30 presenter.present(activityController, animated: true) 30 presenter.present(activityController, animated: true)
31 } 31 }
32} 32}
33
34/// The export menu's entries: text for everyone, the other formats with
35/// advanced exports, and otherwise disabled Pro upsells in their place.
36struct ExportFormatButtons: View {
37 let share: (DomainExportFormat) -> Void
38 /// Labels the entries as exporting a batch.
39 var batch = false
40
41 var body: some View {
42 let noun = batch ? " Batch" : ""
43 Button("Export\(noun) TXT") {
44 share(.text)
45 }
46 if FeatureAccessService.hasAccess(to: .advancedExports) {
47 ForEach(Self.advancedFormats, id: \.label) { format in
48 Button("Export\(noun) \(format.label)") {
49 share(format.format)
50 }
51 }
52 } else {
53 ForEach(Self.advancedFormats, id: \.label) { format in
54 // Inert: disabled Pro upsell affordance.
55 Button(batch ? "Batch \(format.label) • Available in Pro" : "\(format.label) Export • Available in Pro") {}
56 .disabled(true)
57 }
58 }
59 }
60
61 private static let advancedFormats: [(label: String, format: DomainExportFormat)] = [
62 ("CSV", .csv), ("JSON", .json), ("Markdown", .markdown), ("PDF", .pdf),
63 ]
64}
DomainDig/GenericPasswordKeychain.swift added +41
@@ -0,0 +1,41 @@
1import Foundation
2import Security
3
4/// Secrets kept as generic-password keychain items, keyed by account and
5/// readable after first unlock.
6enum GenericPasswordKeychain {
7 /// Replaces any item under `reference`. False when the keychain refuses.
8 static func save(_ secret: String, reference: String) -> Bool {
9 delete(reference: reference)
10 let query: [String: Any] = [
11 kSecClass as String: kSecClassGenericPassword,
12 kSecAttrAccount as String: reference,
13 kSecValueData as String: Data(secret.utf8),
14 kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock
15 ]
16 return SecItemAdd(query as CFDictionary, nil) == errSecSuccess
17 }
18
19 static func secret(reference: String) -> String? {
20 let query: [String: Any] = [
21 kSecClass as String: kSecClassGenericPassword,
22 kSecAttrAccount as String: reference,
23 kSecReturnData as String: true,
24 kSecMatchLimit as String: kSecMatchLimitOne
25 ]
26 var result: CFTypeRef?
27 guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess,
28 let data = result as? Data else {
29 return nil
30 }
31 return String(data: data, encoding: .utf8)
32 }
33
34 static func delete(reference: String) {
35 let query: [String: Any] = [
36 kSecClass as String: kSecClassGenericPassword,
37 kSecAttrAccount as String: reference
38 ]
39 SecItemDelete(query as CFDictionary)
40 }
41}
DomainDig/IntegrationService.swift +23 −46
@@ -646,47 +646,20 @@ private enum HTTPIntegrationClient {
646 646
647private enum IntegrationSecretStore { 647private enum IntegrationSecretStore {
648 static func save(secret: String, reference: String) throws { 648 static func save(secret: String, reference: String) throws {
649 let data = Data(secret.utf8) 649 guard GenericPasswordKeychain.save(secret, reference: reference) else {
650 try? delete(reference: reference)
651
652 let query: [String: Any] = [
653 kSecClass as String: kSecClassGenericPassword,
654 kSecAttrAccount as String: reference,
655 kSecValueData as String: data,
656 kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock
657 ]
658
659 let status = SecItemAdd(query as CFDictionary, nil)
660 guard status == errSecSuccess else {
661 throw IntegrationError.smtp("Could not save integration secret.") 650 throw IntegrationError.smtp("Could not save integration secret.")
662 } 651 }
663 } 652 }
664 653
665 static func secret(reference: String) throws -> String { 654 static func secret(reference: String) throws -> String {
666 let query: [String: Any] = [ 655 guard let secret = GenericPasswordKeychain.secret(reference: reference) else {
667 kSecClass as String: kSecClassGenericPassword,
668 kSecAttrAccount as String: reference,
669 kSecReturnData as String: true,
670 kSecMatchLimit as String: kSecMatchLimitOne
671 ]
672
673 var result: CFTypeRef?
674 let status = SecItemCopyMatching(query as CFDictionary, &result)
675 guard status == errSecSuccess,
676 let data = result as? Data,
677 let secret = String(data: data, encoding: .utf8) else {
678 throw IntegrationError.missingSecret 656 throw IntegrationError.missingSecret
679 } 657 }
680
681 return secret 658 return secret
682 } 659 }
683 660
684 static func delete(reference: String) throws { 661 static func delete(reference: String) throws {
685 let query: [String: Any] = [ 662 GenericPasswordKeychain.delete(reference: reference)
686 kSecClass as String: kSecClassGenericPassword,
687 kSecAttrAccount as String: reference
688 ]
689 SecItemDelete(query as CFDictionary)
690 } 663 }
691} 664}
692 665
@@ -778,23 +751,12 @@ private actor SMTPChannel {
778 // from the connection's queue. 751 // from the connection's queue.
779 let hasResumed = OSAllocatedUnfairLock(initialState: false) 752 let hasResumed = OSAllocatedUnfairLock(initialState: false)
780 connection.stateUpdateHandler = { state in 753 connection.stateUpdateHandler = { state in
781 let isFirst: () -> Bool = { 754 guard let outcome = Self.startOutcome(for: state) else { return }
782 hasResumed.withLock { resumed in 755 let isFirst = hasResumed.withLock { resumed in
783 if resumed { return false } 756 defer { resumed = true }
784 resumed = true 757 return !resumed
785 return true
786 }
787 }
788 switch state {
789 case .ready:
790 if isFirst() { continuation.resume() }
791 case .failed(let error):
792 if isFirst() { continuation.resume(throwing: error) }
793 case .cancelled:
794 if isFirst() { continuation.resume(throwing: IntegrationError.streamClosed) }
795 default:
796 break
797 } 758 }
759 if isFirst { continuation.resume(with: outcome) }
798 } 760 }
799 connection.start(queue: .global(qos: .utility)) 761 connection.start(queue: .global(qos: .utility))
800 } 762 }
@@ -803,6 +765,21 @@ private actor SMTPChannel {
803 startReceiveLoop() 765 startReceiveLoop()
804 } 766 }
805 767
768 /// How a connection state settles `start()`: ready succeeds, failure or
769 /// cancellation throws, and anything else is still in progress.
770 private static func startOutcome(for state: NWConnection.State) -> Result<Void, Error>? {
771 switch state {
772 case .ready:
773 return .success(())
774 case .failed(let error):
775 return .failure(error)
776 case .cancelled:
777 return .failure(IntegrationError.streamClosed)
778 default:
779 return nil
780 }
781 }
782
806 func cancel() { 783 func cancel() {
807 connection.cancel() 784 connection.cancel()
808 } 785 }
DomainDig/ResultSectionViews.swift +154 −124
@@ -234,43 +234,48 @@ struct OwnershipSectionView: View {
234 MessageRowView(text: error, isError: error != "Unavailable") 234 MessageRowView(text: error, isError: error != "Unavailable")
235 .padding(.top, 4) 235 .padding(.top, 4)
236 } 236 }
237 VStack(alignment: .leading, spacing: 8) { 237 historyBlock
238 HStack { 238 }
239 Text("History") 239 }
240 .font(appDensity.font(.caption)) 240 }
241 .foregroundStyle(Color(.appTextSecondary)) 241 }
242 Spacer() 242
243 if let onLoadHistory, history.isEmpty, !historyLoading, !showsHistoryPlaceholder { 243 @ViewBuilder
244 Button("Load") { 244 private var historyBlock: some View {
245 onLoadHistory() 245 VStack(alignment: .leading, spacing: 8) {
246 } 246 HStack {
247 .buttonStyle(.bordered) 247 Text("History")
248 .font(appDensity.font(.caption2)) 248 .font(appDensity.font(.caption))
249 } 249 .foregroundStyle(Color(.appTextSecondary))
250 } 250 Spacer()
251 if historyLoading { 251 if let onLoadHistory, history.isEmpty, !historyLoading, !showsHistoryPlaceholder {
252 ProgressView("Loading history…") 252 Button("Load") {
253 .appLoadingStyle() 253 onLoadHistory()
254 } else if !history.isEmpty { 254 }
255 ForEach(history) { event in 255 .buttonStyle(.bordered)
256 VStack(alignment: .leading, spacing: 3) { 256 .font(appDensity.font(.caption2))
257 Text(event.date.formatted(date: .abbreviated, time: .omitted)) 257 }
258 .font(appDensity.font(.caption2)) 258 }
259 .foregroundStyle(Color(.appTextSecondary)) 259 if historyLoading {
260 Text(event.summary) 260 ProgressView("Loading history…")
261 .font(appDensity.font(.caption)) 261 .appLoadingStyle()
262 Text(event.source) 262 } else if !history.isEmpty {
263 .font(appDensity.font(.caption2)) 263 ForEach(history) { event in
264 .foregroundStyle(Color(.appTextSecondary)) 264 VStack(alignment: .leading, spacing: 3) {
265 } 265 Text(event.date.formatted(date: .abbreviated, time: .omitted))
266 } 266 .font(appDensity.font(.caption2))
267 } else if let historyError { 267 .foregroundStyle(Color(.appTextSecondary))
268 MessageRowView(text: historyError, isError: false) 268 Text(event.summary)
269 } else if showsHistoryPlaceholder { 269 .font(appDensity.font(.caption))
270 MessageRowView(text: "Ownership history available in Pro+", isError: false) 270 Text(event.source)
271 } 271 .font(appDensity.font(.caption2))
272 .foregroundStyle(Color(.appTextSecondary))
272 } 273 }
273 } 274 }
275 } else if let historyError {
276 MessageRowView(text: historyError, isError: false)
277 } else if showsHistoryPlaceholder {
278 MessageRowView(text: "Ownership history available in Pro+", isError: false)
274 } 279 }
275 } 280 }
276 } 281 }
@@ -463,54 +468,69 @@ struct SubdomainsSectionView: View {
463 .buttonStyle(.bordered) 468 .buttonStyle(.bordered)
464 .font(appDensity.font(.caption2)) 469 .font(appDensity.font(.caption2))
465 } 470 }
466 if !groups.isEmpty { 471 groupList
467 Text("Groups") 472 subdomainRows
468 .font(appDensity.font(.caption2)) 473 extendedStatus
469 .foregroundStyle(Color(.appTextSecondary)) 474 }
470 ForEach(groups) { group in 475 }
471 HStack { 476 }
472 Text("\(group.label).*") 477 }
473 .font(appDensity.font(.caption)) 478
474 .foregroundStyle(Color(.statusInfo)) 479 @ViewBuilder
475 Spacer() 480 private var extendedStatus: some View {
476 Text("\(group.subdomains.count)") 481 if extendedLoading {
477 .font(appDensity.font(.caption2)) 482 ProgressView("Loading extended subdomains…")
478 .foregroundStyle(Color(.appTextSecondary)) 483 .appLoadingStyle()
479 } 484 .padding(.top, 4)
480 } 485 } else if extendedCount > 0 {
481 } 486 MessageRowView(text: "\(extendedCount) extended results included", isError: false)
482 ForEach(rows) { row in 487 .padding(.top, 4)
483 HStack(spacing: 8) { 488 } else if let extendedError {
484 Text(row.hostname) 489 MessageRowView(text: extendedError, isError: false)
485 .font(appDensity.font(.caption)) 490 .padding(.top, 4)
486 .foregroundStyle(.primary) 491 } else if showsExtendedPlaceholder {
487 .textSelection(.enabled) 492 MessageRowView(text: "Extended subdomain discovery available in Pro+", isError: false)
488 Spacer() 493 .padding(.top, 4)
489 if row.isInteresting { 494 }
490 Text("Interesting") 495 }
491 .font(.system(.caption2, design: .monospaced)) 496
492 .foregroundStyle(Color(.statusWarning)) 497 @ViewBuilder
493 .padding(.horizontal, 8) 498 private var groupList: some View {
494 .padding(.vertical, 4) 499 if !groups.isEmpty {
495 .background(Color(.statusWarningSurface)) 500 Text("Groups")
496 .clipShape(Capsule()) 501 .font(appDensity.font(.caption2))
497 } 502 .foregroundStyle(Color(.appTextSecondary))
498 } 503 ForEach(groups) { group in
499 } 504 HStack {
500 if extendedLoading { 505 Text("\(group.label).*")
501 ProgressView("Loading extended subdomains…") 506 .font(appDensity.font(.caption))
502 .appLoadingStyle() 507 .foregroundStyle(Color(.statusInfo))
503 .padding(.top, 4) 508 Spacer()
504 } else if extendedCount > 0 { 509 Text("\(group.subdomains.count)")
505 MessageRowView(text: "\(extendedCount) extended results included", isError: false) 510 .font(appDensity.font(.caption2))
506 .padding(.top, 4) 511 .foregroundStyle(Color(.appTextSecondary))
507 } else if let extendedError { 512 }
508 MessageRowView(text: extendedError, isError: false) 513 }
509 .padding(.top, 4) 514 }
510 } else if showsExtendedPlaceholder { 515 }
511 MessageRowView(text: "Extended subdomain discovery available in Pro+", isError: false) 516
512 .padding(.top, 4) 517 @ViewBuilder
513 } 518 private var subdomainRows: some View {
519 ForEach(rows) { row in
520 HStack(spacing: 8) {
521 Text(row.hostname)
522 .font(appDensity.font(.caption))
523 .foregroundStyle(.primary)
524 .textSelection(.enabled)
525 Spacer()
526 if row.isInteresting {
527 Text("Interesting")
528 .font(.system(.caption2, design: .monospaced))
529 .foregroundStyle(Color(.statusWarning))
530 .padding(.horizontal, 8)
531 .padding(.vertical, 4)
532 .background(Color(.statusWarningSurface))
533 .clipShape(Capsule())
514 } 534 }
515 } 535 }
516 } 536 }
@@ -576,21 +596,7 @@ struct DNSSectionView: View {
576 } else if let sectionError, sections.isEmpty { 596 } else if let sectionError, sections.isEmpty {
577 MessageCardView(text: sectionError, isError: true) 597 MessageCardView(text: sectionError, isError: true)
578 } else { 598 } else {
579 if dnsProvenance != nil { 599 provenanceCard
580 CardView(allowsHorizontalScroll: false) {
581 SectionTrustMetadataView(provenance: dnsProvenance, confidence: nil)
582 if let patternSummary {
583 if !patternSummary.providers.isEmpty {
584 MessageRowView(text: "Providers: \(patternSummary.providers.joined(separator: ", "))", isError: false)
585 }
586 if !patternSummary.patterns.isEmpty {
587 ForEach(Array(patternSummary.patterns.enumerated()), id: \.offset) { _, pattern in
588 MessageRowView(text: pattern, isError: false)
589 }
590 }
591 }
592 }
593 }
594 ForEach(sections) { section in 600 ForEach(sections) { section in
595 CardView { 601 CardView {
596 Text(section.title) 602 Text(section.title)
@@ -643,33 +649,57 @@ struct DNSSectionView: View {
643 .font(appDensity.font(.caption2)) 649 .font(appDensity.font(.caption2))
644 } 650 }
645 } 651 }
646 if historyLoading { 652 historyContent
647 ProgressView("Loading DNS history…") 653 }
648 .appLoadingStyle() 654 }
649 } else if !history.isEmpty { 655 }
650 ForEach(history) { event in 656 }
651 VStack(alignment: .leading, spacing: 3) { 657
652 Text(event.date.formatted(date: .abbreviated, time: .omitted)) 658 @ViewBuilder
653 .font(appDensity.font(.caption2)) 659 private var historyContent: some View {
654 .foregroundStyle(Color(.appTextSecondary)) 660 if historyLoading {
655 Text(event.summary) 661 ProgressView("Loading DNS history…")
656 .font(appDensity.font(.caption)) 662 .appLoadingStyle()
657 if !event.aRecords.isEmpty { 663 } else if !history.isEmpty {
658 Text("A: \(event.aRecords.joined(separator: ", "))") 664 ForEach(history) { event in
659 .font(appDensity.font(.caption2)) 665 VStack(alignment: .leading, spacing: 3) {
660 .foregroundStyle(Color(.appTextSecondary)) 666 Text(event.date.formatted(date: .abbreviated, time: .omitted))
661 } 667 .font(appDensity.font(.caption2))
662 if !event.nameservers.isEmpty { 668 .foregroundStyle(Color(.appTextSecondary))
663 Text("NS: \(event.nameservers.joined(separator: ", "))") 669 Text(event.summary)
664 .font(appDensity.font(.caption2)) 670 .font(appDensity.font(.caption))
665 .foregroundStyle(Color(.appTextSecondary)) 671 if !event.aRecords.isEmpty {
666 } 672 Text("A: \(event.aRecords.joined(separator: ", "))")
667 } 673 .font(appDensity.font(.caption2))
674 .foregroundStyle(Color(.appTextSecondary))
675 }
676 if !event.nameservers.isEmpty {
677 Text("NS: \(event.nameservers.joined(separator: ", "))")
678 .font(appDensity.font(.caption2))
679 .foregroundStyle(Color(.appTextSecondary))
680 }
681 }
682 }
683 } else if let historyError {
684 MessageRowView(text: historyError, isError: false)
685 } else if showsHistoryPlaceholder {
686 MessageRowView(text: "DNS history available in Pro+", isError: false)
687 }
688 }
689
690 @ViewBuilder
691 private var provenanceCard: some View {
692 if dnsProvenance != nil {
693 CardView(allowsHorizontalScroll: false) {
694 SectionTrustMetadataView(provenance: dnsProvenance, confidence: nil)
695 if let patternSummary {
696 if !patternSummary.providers.isEmpty {
697 MessageRowView(text: "Providers: \(patternSummary.providers.joined(separator: ", "))", isError: false)
698 }
699 if !patternSummary.patterns.isEmpty {
700 ForEach(Array(patternSummary.patterns.enumerated()), id: \.offset) { _, pattern in
701 MessageRowView(text: pattern, isError: false)
668 } 702 }
669 } else if let historyError {
670 MessageRowView(text: historyError, isError: false)
671 } else if showsHistoryPlaceholder {
672 MessageRowView(text: "DNS history available in Pro+", isError: false)
673 } 703 }
674 } 704 }
675 } 705 }
DomainDig/SettingsViews.swift +16 −35
@@ -483,41 +483,14 @@ private struct MonitoringSettingsView: View {
483 ) 483 )
484 484
485 if viewModel.monitoringSettings.quietHours != nil { 485 if viewModel.monitoringSettings.quietHours != nil {
486 Picker( 486 hourPicker("Quiet Starts", selection: Binding(
487 "Quiet Starts", 487 get: { quietHoursStart },
488 selection: Binding( 488 set: { viewModel.setMonitoringQuietHours(startHour: $0, endHour: quietHoursEnd, isEnabled: true) }
489 get: { quietHoursStart }, 489 ))
490 set: { startHour in 490 hourPicker("Quiet Ends", selection: Binding(
491 viewModel.setMonitoringQuietHours( 491 get: { quietHoursEnd },
492 startHour: startHour, 492 set: { viewModel.setMonitoringQuietHours(startHour: quietHoursStart, endHour: $0, isEnabled: true) }
493 endHour: quietHoursEnd, 493 ))
494 isEnabled: true
495 )
496 }
497 )
498 ) {
499 ForEach(0..<24, id: \.self) { hour in
500 Text(Self.monitoringHourLabel(for: hour)).tag(hour)
501 }
502 }
503
504 Picker(
505 "Quiet Ends",
506 selection: Binding(
507 get: { quietHoursEnd },
508 set: { endHour in
509 viewModel.setMonitoringQuietHours(
510 startHour: quietHoursStart,
511 endHour: endHour,
512 isEnabled: true
513 )
514 }
515 )
516 ) {
517 ForEach(0..<24, id: \.self) { hour in
518 Text(Self.monitoringHourLabel(for: hour)).tag(hour)
519 }
520 }
521 } 494 }
522 495
523 Picker( 496 Picker(
@@ -597,6 +570,14 @@ private struct MonitoringSettingsView: View {
597 } 570 }
598 } 571 }
599 572
573 private func hourPicker(_ title: String, selection: Binding<Int>) -> some View {
574 Picker(title, selection: selection) {
575 ForEach(0..<24, id: \.self) { hour in
576 Text(Self.monitoringHourLabel(for: hour)).tag(hour)
577 }
578 }
579 }
580
600 private static func monitoringHourLabel(for hour: Int) -> String { 581 private static func monitoringHourLabel(for hour: Int) -> String {
601 let formatter = DateFormatter() 582 let formatter = DateFormatter()
602 formatter.dateFormat = "h a" 583 formatter.dateFormat = "h a"
DomainDig/WatchlistView.swift +56 −89
@@ -150,36 +150,7 @@ struct WatchlistView: View {
150 } 150 }
151 } 151 }
152 152
153 Button("Export TXT") { 153 ExportFormatButtons(share: shareTrackedDomains)
154 shareTrackedDomains(format: .text)
155 }
156
157 if FeatureAccessService.hasAccess(to: .advancedExports) {
158 Button("Export CSV") {
159 shareTrackedDomains(format: .csv)
160 }
161
162 Button("Export JSON") {
163 shareTrackedDomains(format: .json)
164 }
165
166 Button("Export Markdown") {
167 shareTrackedDomains(format: .markdown)
168 }
169
170 Button("Export PDF") {
171 shareTrackedDomains(format: .pdf)
172 }
173 } else {
174 Button("CSV Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
175 .disabled(true)
176 Button("JSON Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
177 .disabled(true)
178 Button("Markdown Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
179 .disabled(true)
180 Button("PDF Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
181 .disabled(true)
182 }
183 } label: { 154 } label: {
184 Image(systemName: "line.3.horizontal.decrease.circle") 155 Image(systemName: "line.3.horizontal.decrease.circle")
185 } 156 }
@@ -313,76 +284,72 @@ struct WatchlistView: View {
313 } 284 }
314 .buttonStyle(.plain) 285 .buttonStyle(.plain)
315 .swipeActions(edge: .leading, allowsFullSwipe: false) { 286 .swipeActions(edge: .leading, allowsFullSwipe: false) {
316 Button { 287 refreshButton(trackedDomain)
317 AppHaptics.refresh() 288 .tint(Color(.statusInfo))
318 viewModel.refreshTrackedDomain(trackedDomain) 289 pinButton(trackedDomain)
319 } label: { 290 .tint(Color(.statusWarning))
320 Label("Refresh", systemImage: "arrow.clockwise")
321 }
322 .tint(Color(.statusInfo))
323
324 Button {
325 viewModel.togglePinned(for: trackedDomain)
326 } label: {
327 Label(trackedDomain.isPinned ? "Unpin" : "Pin", systemImage: trackedDomain.isPinned ? "pin.slash" : "pin")
328 }
329 .tint(Color(.statusWarning))
330 } 291 }
331 .swipeActions(edge: .trailing, allowsFullSwipe: false) { 292 .swipeActions(edge: .trailing, allowsFullSwipe: false) {
332 Button { 293 refreshButton(trackedDomain)
333 AppHaptics.refresh() 294 .tint(Color(.statusInfo))
334 viewModel.refreshTrackedDomain(trackedDomain) 295 deleteButton(trackedDomain)
335 } label: {
336 Label("Refresh", systemImage: "arrow.clockwise")
337 }
338 .tint(Color(.statusInfo))
339
340 if viewModel.canDelete(trackedDomain) {
341 Button(role: .destructive) {
342 viewModel.deleteTrackedDomain(trackedDomain)
343 } label: {
344 Label("Delete", systemImage: "trash")
345 }
346 }
347 } 296 }
348 .contextMenu { 297 .contextMenu {
349 Button { 298 rowMenu(trackedDomain)
350 AppHaptics.refresh() 299 }
351 viewModel.refreshTrackedDomain(trackedDomain) 300 .listRowBackground(Color(.appSurface))
352 } label: { 301 }
353 Label("Refresh", systemImage: "arrow.clockwise")
354 }
355 302
356 Button { 303 @ViewBuilder
357 dismiss() 304 private func rowMenu(_ trackedDomain: TrackedDomain) -> some View {
358 viewModel.rerunInspection(for: trackedDomain) 305 refreshButton(trackedDomain)
359 } label: {
360 Label("Open Inspection", systemImage: "magnifyingglass")
361 }
362 306
363 Button { 307 Button {
364 viewModel.togglePinned(for: trackedDomain) 308 dismiss()
365 } label: { 309 viewModel.rerunInspection(for: trackedDomain)
366 Label(trackedDomain.isPinned ? "Unpin" : "Pin", systemImage: trackedDomain.isPinned ? "pin.slash" : "pin") 310 } label: {
367 } 311 Label("Open Inspection", systemImage: "magnifyingglass")
312 }
313
314 pinButton(trackedDomain)
368 .disabled(!viewModel.canEdit(trackedDomain)) 315 .disabled(!viewModel.canEdit(trackedDomain))
369 316
370 Button { 317 Button {
371 // The system sharing UI manages participants and permissions. 318 // The system sharing UI manages participants and permissions.
372 } label: { 319 } label: {
373 Label(trackedDomain.collaboration?.isShared == true ? "Shared" : "Private", systemImage: "person.2") 320 Label(trackedDomain.collaboration?.isShared == true ? "Shared" : "Private", systemImage: "person.2")
374 } 321 }
375 .disabled(true) 322 .disabled(true)
376 323
377 if viewModel.canDelete(trackedDomain) { 324 deleteButton(trackedDomain)
378 Button(role: .destructive) { 325 }
379 viewModel.deleteTrackedDomain(trackedDomain) 326
380 } label: { 327 private func refreshButton(_ trackedDomain: TrackedDomain) -> some View {
381 Label("Delete", systemImage: "trash") 328 Button {
382 } 329 AppHaptics.refresh()
330 viewModel.refreshTrackedDomain(trackedDomain)
331 } label: {
332 Label("Refresh", systemImage: "arrow.clockwise")
333 }
334 }
335
336 private func pinButton(_ trackedDomain: TrackedDomain) -> some View {
337 Button {
338 viewModel.togglePinned(for: trackedDomain)
339 } label: {
340 Label(trackedDomain.isPinned ? "Unpin" : "Pin", systemImage: trackedDomain.isPinned ? "pin.slash" : "pin")
341 }
342 }
343
344 @ViewBuilder
345 private func deleteButton(_ trackedDomain: TrackedDomain) -> some View {
346 if viewModel.canDelete(trackedDomain) {
347 Button(role: .destructive) {
348 viewModel.deleteTrackedDomain(trackedDomain)
349 } label: {
350 Label("Delete", systemImage: "trash")
383 } 351 }
384 } 352 }
385 .listRowBackground(Color(.appSurface))
386 } 353 }
387 354
388 private var batchSummaryBinding: Binding<BatchSweepSummary?> { 355 private var batchSummaryBinding: Binding<BatchSweepSummary?> {
DomainDig/WorkflowsView.swift +8 −71
@@ -237,32 +237,7 @@ struct WorkflowDetailView: View {
237 if latestSummary != nil { 237 if latestSummary != nil {
238 Toggle("Export all domains", isOn: $includeAllExports) 238 Toggle("Export all domains", isOn: $includeAllExports)
239 Menu { 239 Menu {
240 Button("Export TXT") { 240 ExportFormatButtons(share: shareWorkflowResults)
241 shareWorkflowResults(format: .text)
242 }
243 if FeatureAccessService.hasAccess(to: .advancedExports) {
244 Button("Export CSV") {
245 shareWorkflowResults(format: .csv)
246 }
247 Button("Export JSON") {
248 shareWorkflowResults(format: .json)
249 }
250 Button("Export Markdown") {
251 shareWorkflowResults(format: .markdown)
252 }
253 Button("Export PDF") {
254 shareWorkflowResults(format: .pdf)
255 }
256 } else {
257 Button("CSV Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
258 .disabled(true)
259 Button("JSON Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
260 .disabled(true)
261 Button("Markdown Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
262 .disabled(true)
263 Button("PDF Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
264 .disabled(true)
265 }
266 } label: { 241 } label: {
267 Label("Export Results", systemImage: "square.and.arrow.up") 242 Label("Export Results", systemImage: "square.and.arrow.up")
268 } 243 }
@@ -512,56 +487,18 @@ struct WorkflowRunSummaryView: View {
512 } 487 }
513 } 488 }
514 489
515 Section(visibleResults.isEmpty ? "Meaningful Changes" : "Results") { 490 BatchResultsSection(
516 if visibleResults.isEmpty { 491 viewModel: viewModel,
517 Text("No domains with meaningful changes or warnings") 492 results: visibleResults,
518 .font(.system(.caption, design: .monospaced)) 493 emptyTitle: "Meaningful Changes",
519 .foregroundStyle(Color(.appTextSecondary)) 494 emptyText: "No domains with meaningful changes or warnings"
520 } else { 495 )
521 ForEach(visibleResults) { result in
522 if let entry = viewModel.historyEntry(for: result) {
523 NavigationLink {
524 HistoryDetailView(viewModel: viewModel, entry: entry)
525 } label: {
526 BatchResultRowView(result: result)
527 }
528 } else {
529 BatchResultRowView(result: result)
530 }
531 }
532 }
533 }
534 } 496 }
535 .navigationTitle("Workflow Summary") 497 .navigationTitle("Workflow Summary")
536 .toolbar { 498 .toolbar {
537 ToolbarItemGroup(placement: .topBarTrailing) { 499 ToolbarItemGroup(placement: .topBarTrailing) {
538 Menu { 500 Menu {
539 Button("Export TXT") { 501 ExportFormatButtons(share: share)
540 share(format: .text)
541 }
542 if FeatureAccessService.hasAccess(to: .advancedExports) {
543 Button("Export CSV") {
544 share(format: .csv)
545 }
546 Button("Export JSON") {
547 share(format: .json)
548 }
549 Button("Export Markdown") {
550 share(format: .markdown)
551 }
552 Button("Export PDF") {
553 share(format: .pdf)
554 }
555 } else {
556 Button("CSV Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
557 .disabled(true)
558 Button("JSON Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
559 .disabled(true)
560 Button("Markdown Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
561 .disabled(true)
562 Button("PDF Export • Available in Pro") { /* Inert: disabled Pro upsell affordance. */ }
563 .disabled(true)
564 }
565 } label: { 502 } label: {
566 Image(systemName: "square.and.arrow.up") 503 Image(systemName: "square.and.arrow.up")
567 } 504 }
DomainInspectionService.swift +124 −219
@@ -19,11 +19,7 @@ struct DomainInspectionService {
19 let startedAt = Date() 19 let startedAt = Date()
20 let resolverDisplayName = DNSLookupService.currentResolverDisplayName() 20 let resolverDisplayName = DNSLookupService.currentResolverDisplayName()
21 let resolverURLString = DNSLookupService.currentResolverURLString() 21 let resolverURLString = DNSLookupService.currentResolverURLString()
22 var cachedSections = Set<LookupSectionKind>() 22 var ledger = InspectionLedger(resolverDisplayName: resolverDisplayName)
23 var sectionSources: [LookupResultSource] = []
24 var provenanceBySection: [LookupSectionKind: SectionProvenance] = [:]
25 var dataSources = Set<String>()
26 var errorDetails: [LookupSectionKind: InspectionFailure] = [:]
27 23
28 async let dnsFetch = runtime.dns(domain: normalizedDomain) 24 async let dnsFetch = runtime.dns(domain: normalizedDomain)
29 async let availabilityFetch = runtime.availability(domain: normalizedDomain) 25 async let availabilityFetch = runtime.availability(domain: normalizedDomain)
@@ -37,110 +33,46 @@ struct DomainInspectionService {
37 let resolvedDNS = await dnsFetch 33 let resolvedDNS = await dnsFetch
38 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=dns source=\(resolvedDNS.source.rawValue)") 34 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=dns source=\(resolvedDNS.source.rawValue)")
39 let dnsResult = normalizeErrors(in: resolvedDNS.value) 35 let dnsResult = normalizeErrors(in: resolvedDNS.value)
40 track( 36 ledger.track(.dns, source: resolvedDNS.source)
41 .dns, 37 ledger.captureFailure(for: .dns, result: dnsResult)
42 source: resolvedDNS.source,
43 provenance: provenance(for: .dns, source: resolvedDNS.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
44 cachedSections: &cachedSections,
45 sectionSources: &sectionSources,
46 provenanceBySection: &provenanceBySection,
47 dataSources: &dataSources
48 )
49 captureFailure(for: .dns, result: dnsResult, into: &errorDetails)
50 38
51 let availability = await availabilityFetch 39 let availability = await availabilityFetch
52 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=availability source=\(availability.source.rawValue)") 40 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=availability source=\(availability.source.rawValue)")
53 track( 41 ledger.track(.availability, source: availability.source)
54 .availability,
55 source: availability.source,
56 provenance: provenance(for: .availability, source: availability.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
57 cachedSections: &cachedSections,
58 sectionSources: &sectionSources,
59 provenanceBySection: &provenanceBySection,
60 dataSources: &dataSources
61 )
62 42
63 let resolvedSSL = await sslFetch 43 let resolvedSSL = await sslFetch
64 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=ssl source=\(resolvedSSL.source.rawValue)") 44 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=ssl source=\(resolvedSSL.source.rawValue)")
65 let sslResult = normalizeErrors(in: resolvedSSL.value) 45 let sslResult = normalizeErrors(in: resolvedSSL.value)
66 track( 46 ledger.track(.ssl, source: resolvedSSL.source)
67 .ssl, 47 ledger.captureFailure(for: .ssl, result: sslResult)
68 source: resolvedSSL.source,
69 provenance: provenance(for: .ssl, source: resolvedSSL.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
70 cachedSections: &cachedSections,
71 sectionSources: &sectionSources,
72 provenanceBySection: &provenanceBySection,
73 dataSources: &dataSources
74 )
75 captureFailure(for: .ssl, result: sslResult, into: &errorDetails)
76 48
77 let hsts = await hstsFetch 49 let hsts = await hstsFetch
78 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=hsts source=\(hsts.source.rawValue)") 50 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=hsts source=\(hsts.source.rawValue)")
79 track( 51 ledger.track(.hsts, source: hsts.source)
80 .hsts,
81 source: hsts.source,
82 provenance: provenance(for: .hsts, source: hsts.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
83 cachedSections: &cachedSections,
84 sectionSources: &sectionSources,
85 provenanceBySection: &provenanceBySection,
86 dataSources: &dataSources
87 )
88 52
89 let http = await httpFetch 53 let http = await httpFetch
90 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=http source=\(http.source.rawValue)") 54 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=http source=\(http.source.rawValue)")
91 let httpResult = normalizeErrors(in: http.value) 55 let httpResult = normalizeErrors(in: http.value)
92 track( 56 ledger.track(.httpHeaders, source: http.source)
93 .httpHeaders, 57 ledger.captureFailure(for: .httpHeaders, result: httpResult)
94 source: http.source,
95 provenance: provenance(for: .httpHeaders, source: http.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
96 cachedSections: &cachedSections,
97 sectionSources: &sectionSources,
98 provenanceBySection: &provenanceBySection,
99 dataSources: &dataSources
100 )
101 captureFailure(for: .httpHeaders, result: httpResult, into: &errorDetails)
102 58
103 let resolvedOwnership = await ownershipFetch 59 let resolvedOwnership = await ownershipFetch
104 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=ownership source=\(resolvedOwnership.source.rawValue)") 60 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=ownership source=\(resolvedOwnership.source.rawValue)")
105 let ownershipResult = normalizeErrors(in: resolvedOwnership.value) 61 let ownershipResult = normalizeErrors(in: resolvedOwnership.value)
106 track( 62 ledger.track(.ownership, source: resolvedOwnership.source)
107 .ownership, 63 ledger.captureFailure(for: .ownership, result: ownershipResult)
108 source: resolvedOwnership.source,
109 provenance: provenance(for: .ownership, source: resolvedOwnership.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
110 cachedSections: &cachedSections,
111 sectionSources: &sectionSources,
112 provenanceBySection: &provenanceBySection,
113 dataSources: &dataSources
114 )
115 captureFailure(for: .ownership, result: ownershipResult, into: &errorDetails)
116 64
117 let redirects = await redirectFetch 65 let redirects = await redirectFetch
118 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=redirect source=\(redirects.source.rawValue)") 66 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=redirect source=\(redirects.source.rawValue)")
119 let redirectResult = normalizeErrors(in: redirects.value) 67 let redirectResult = normalizeErrors(in: redirects.value)
120 track( 68 ledger.track(.redirectChain, source: redirects.source)
121 .redirectChain, 69 ledger.captureFailure(for: .redirectChain, result: redirectResult)
122 source: redirects.source,
123 provenance: provenance(for: .redirectChain, source: redirects.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
124 cachedSections: &cachedSections,
125 sectionSources: &sectionSources,
126 provenanceBySection: &provenanceBySection,
127 dataSources: &dataSources
128 )
129 captureFailure(for: .redirectChain, result: redirectResult, into: &errorDetails)
130 70
131 let resolvedSubdomains = await subdomainFetch 71 let resolvedSubdomains = await subdomainFetch
132 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=subdomains source=\(resolvedSubdomains.source.rawValue)") 72 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=subdomains source=\(resolvedSubdomains.source.rawValue)")
133 let subdomainResult = normalizeErrors(in: resolvedSubdomains.value) 73 let subdomainResult = normalizeErrors(in: resolvedSubdomains.value)
134 track( 74 ledger.track(.subdomains, source: resolvedSubdomains.source)
135 .subdomains, 75 ledger.captureFailure(for: .subdomains, result: subdomainResult)
136 source: resolvedSubdomains.source,
137 provenance: provenance(for: .subdomains, source: resolvedSubdomains.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
138 cachedSections: &cachedSections,
139 sectionSources: &sectionSources,
140 provenanceBySection: &provenanceBySection,
141 dataSources: &dataSources
142 )
143 captureFailure(for: .subdomains, result: subdomainResult, into: &errorDetails)
144 76
145 let dnsSections = mapServiceResult(dnsResult, emptyValue: []) 77 let dnsSections = mapServiceResult(dnsResult, emptyValue: [])
146 let sslInfo = mapOptionalValueServiceResult(sslResult) 78 let sslInfo = mapOptionalValueServiceResult(sslResult)
@@ -158,85 +90,46 @@ struct DomainInspectionService {
158 let canReuseDNSDependents = canReuseDependentSections(from: previousSnapshot, dnsSections: dnsSections.value) 90 let canReuseDNSDependents = canReuseDependentSections(from: previousSnapshot, dnsSections: dnsSections.value)
159 let canReuseIPDependents = canReuseIPBasedSections(from: previousSnapshot, primaryIP: primaryIP) 91 let canReuseIPDependents = canReuseIPBasedSections(from: previousSnapshot, primaryIP: primaryIP)
160 92
161 let reachabilityOutcome: CachedLookupResult<ServiceResult<[PortReachability]>> 93 let reachabilityOutcome = await whenRoutable(hasNetworkTarget) {
162 if hasNetworkTarget { 94 await runtime.reachability(domain: normalizedDomain)
163 reachabilityOutcome = await runtime.reachability(domain: normalizedDomain)
164 } else {
165 reachabilityOutcome = CachedLookupResult(value: .empty("No routable address available"), source: .live)
166 } 95 }
167 let reachabilityResult = normalizeErrors(in: reachabilityOutcome.value) 96 let reachabilityResult = normalizeErrors(in: reachabilityOutcome.value)
168 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=reachability hasNetworkTarget=\(hasNetworkTarget) source=\(reachabilityOutcome.source.rawValue)") 97 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=reachability hasNetworkTarget=\(hasNetworkTarget) source=\(reachabilityOutcome.source.rawValue)")
169 track( 98 ledger.track(.reachability, source: reachabilityOutcome.source)
170 .reachability,
171 source: reachabilityOutcome.source,
172 provenance: provenance(for: .reachability, source: reachabilityOutcome.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
173 cachedSections: &cachedSections,
174 sectionSources: &sectionSources,
175 provenanceBySection: &provenanceBySection,
176 dataSources: &dataSources
177 )
178 if hasNetworkTarget { 99 if hasNetworkTarget {
179 captureFailure(for: .reachability, result: reachabilityResult, into: &errorDetails) 100 ledger.captureFailure(for: .reachability, result: reachabilityResult)
180 } 101 }
181 let reachabilityResultValue = mapServiceResult(reachabilityResult, emptyValue: []) 102 let reachabilityResultValue = mapServiceResult(reachabilityResult, emptyValue: [])
182 103
183 let portScanOutcome: CachedLookupResult<ServiceResult<[PortScanResult]>> 104 let portScanOutcome = await whenRoutable(hasNetworkTarget) {
184 if hasNetworkTarget { 105 await runtime.portScan(domain: normalizedDomain)
185 portScanOutcome = await runtime.portScan(domain: normalizedDomain)
186 } else {
187 portScanOutcome = CachedLookupResult(value: .empty("No routable address available"), source: .live)
188 } 106 }
189 let portScanResult = normalizeErrors(in: portScanOutcome.value) 107 let portScanResult = normalizeErrors(in: portScanOutcome.value)
190 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=portScan hasNetworkTarget=\(hasNetworkTarget) source=\(portScanOutcome.source.rawValue)") 108 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=portScan hasNetworkTarget=\(hasNetworkTarget) source=\(portScanOutcome.source.rawValue)")
191 track( 109 ledger.track(.portScan, source: portScanOutcome.source)
192 .portScan,
193 source: portScanOutcome.source,
194 provenance: provenance(for: .portScan, source: portScanOutcome.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
195 cachedSections: &cachedSections,
196 sectionSources: &sectionSources,
197 provenanceBySection: &provenanceBySection,
198 dataSources: &dataSources
199 )
200 if hasNetworkTarget { 110 if hasNetworkTarget {
201 captureFailure(for: .portScan, result: portScanResult, into: &errorDetails) 111 ledger.captureFailure(for: .portScan, result: portScanResult)
202 } 112 }
203 let portScanResults = hasNetworkTarget 113 let portScanResults = hasNetworkTarget
204 ? await mapPortScanResult(portScanResult, domain: normalizedDomain) 114 ? await mapPortScanResult(portScanResult, domain: normalizedDomain)
205 : (value: [], message: nil) 115 : (value: [], message: nil)
206 116
207 let emailOutcome: CachedLookupResult<ServiceResult<EmailSecurityResult>> 117 let emailOutcome = await reusingPrevious(
208 if canReuseDNSDependents, let previousSnapshot, let emailSecurity = previousSnapshot.emailSecurity { 118 previousSnapshot?.emailSecurity,
209 emailOutcome = CachedLookupResult(value: .success(emailSecurity), source: .cached) 119 error: previousSnapshot?.emailSecurityError,
210 } else if canReuseDNSDependents, let previousSnapshot, let error = previousSnapshot.emailSecurityError { 120 when: canReuseDNSDependents
211 emailOutcome = CachedLookupResult(value: .error(error), source: .cached) 121 ) {
212 } else { 122 await runtime.email(domain: normalizedDomain, txtRecords: txtRecords)
213 emailOutcome = await runtime.email(domain: normalizedDomain, txtRecords: txtRecords)
214 } 123 }
215 let normalizedEmailResult = normalizeErrors(in: emailOutcome.value) 124 let normalizedEmailResult = normalizeErrors(in: emailOutcome.value)
216 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=email source=\(emailOutcome.source.rawValue)") 125 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=email source=\(emailOutcome.source.rawValue)")
217 track( 126 ledger.track(.emailSecurity, source: emailOutcome.source)
218 .emailSecurity, 127 ledger.captureFailure(for: .emailSecurity, result: normalizedEmailResult)
219 source: emailOutcome.source,
220 provenance: provenance(for: .emailSecurity, source: emailOutcome.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
221 cachedSections: &cachedSections,
222 sectionSources: &sectionSources,
223 provenanceBySection: &provenanceBySection,
224 dataSources: &dataSources
225 )
226 captureFailure(for: .emailSecurity, result: normalizedEmailResult, into: &errorDetails)
227 128
228 let suggestionsOutcome: CachedLookupResult<[DomainSuggestionResult]> 129 let suggestionsOutcome: CachedLookupResult<[DomainSuggestionResult]>
229 if availability.value.status == .registered { 130 if availability.value.status == .registered {
230 suggestionsOutcome = await runtime.suggestions(domain: normalizedDomain) 131 suggestionsOutcome = await runtime.suggestions(domain: normalizedDomain)
231 track( 132 ledger.track(.suggestions, source: suggestionsOutcome.source)
232 .suggestions,
233 source: suggestionsOutcome.source,
234 provenance: provenance(for: .suggestions, source: suggestionsOutcome.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
235 cachedSections: &cachedSections,
236 sectionSources: &sectionSources,
237 provenanceBySection: &provenanceBySection,
238 dataSources: &dataSources
239 )
240 } else { 133 } else {
241 suggestionsOutcome = CachedLookupResult(value: [], source: .live) 134 suggestionsOutcome = CachedLookupResult(value: [], source: .live)
242 } 135 }
@@ -244,48 +137,26 @@ struct DomainInspectionService {
244 let ptrOutcome: CachedLookupResult<ServiceResult<String>>? 137 let ptrOutcome: CachedLookupResult<ServiceResult<String>>?
245 let geoOutcome: CachedLookupResult<ServiceResult<IPGeolocation>>? 138 let geoOutcome: CachedLookupResult<ServiceResult<IPGeolocation>>?
246 if let primaryIP { 139 if let primaryIP {
247 if canReuseIPDependents, let previousSnapshot, let ptrRecord = previousSnapshot.ptrRecord { 140 let ptr = await reusingPrevious(
248 ptrOutcome = CachedLookupResult(value: .success(ptrRecord), source: .cached) 141 previousSnapshot?.ptrRecord,
249 } else if canReuseIPDependents, let previousSnapshot, let ptrError = previousSnapshot.ptrError { 142 error: previousSnapshot?.ptrError,
250 ptrOutcome = CachedLookupResult(value: .error(ptrError), source: .cached) 143 when: canReuseIPDependents
251 } else { 144 ) {
252 ptrOutcome = await runtime.ptr(ip: primaryIP, resolverURLString: resolverURLString) 145 await runtime.ptr(ip: primaryIP, resolverURLString: resolverURLString)
253 } 146 }
254 147 let geo = await reusingPrevious(
255 if canReuseIPDependents, let previousSnapshot, let ipGeolocation = previousSnapshot.ipGeolocation { 148 previousSnapshot?.ipGeolocation,
256 geoOutcome = CachedLookupResult(value: .success(ipGeolocation), source: .cached) 149 error: previousSnapshot?.ipGeolocationError,
257 } else if canReuseIPDependents, let previousSnapshot, let ipGeolocationError = previousSnapshot.ipGeolocationError { 150 when: canReuseIPDependents
258 geoOutcome = CachedLookupResult(value: .error(ipGeolocationError), source: .cached) 151 ) {
259 } else { 152 await runtime.ipGeolocation(ip: primaryIP)
260 geoOutcome = await runtime.ipGeolocation(ip: primaryIP)
261 }
262
263 if let ptrOutcome {
264 let normalizedPTRResult = normalizeErrors(in: ptrOutcome.value)
265 track(
266 .ptr,
267 source: ptrOutcome.source,
268 provenance: provenance(for: .ptr, source: ptrOutcome.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
269 cachedSections: &cachedSections,
270 sectionSources: &sectionSources,
271 provenanceBySection: &provenanceBySection,
272 dataSources: &dataSources
273 )
274 captureFailure(for: .ptr, result: normalizedPTRResult, into: &errorDetails)
275 }
276 if let geoOutcome {
277 let normalizedGeoResult = normalizeErrors(in: geoOutcome.value)
278 track(
279 .ipGeolocation,
280 source: geoOutcome.source,
281 provenance: provenance(for: .ipGeolocation, source: geoOutcome.source, collectedAt: Date(), resolverDisplayName: resolverDisplayName),
282 cachedSections: &cachedSections,
283 sectionSources: &sectionSources,
284 provenanceBySection: &provenanceBySection,
285 dataSources: &dataSources
286 )
287 captureFailure(for: .ipGeolocation, result: normalizedGeoResult, into: &errorDetails)
288 } 153 }
154 ledger.track(.ptr, source: ptr.source)
155 ledger.captureFailure(for: .ptr, result: normalizeErrors(in: ptr.value))
156 ledger.track(.ipGeolocation, source: geo.source)
157 ledger.captureFailure(for: .ipGeolocation, result: normalizeErrors(in: geo.value))
158 ptrOutcome = ptr
159 geoOutcome = geo
289 } else { 160 } else {
290 ptrOutcome = nil 161 ptrOutcome = nil
291 geoOutcome = nil 162 geoOutcome = nil
@@ -294,12 +165,12 @@ struct DomainInspectionService {
294 let emailSecurity = mapOptionalValueServiceResult(normalizedEmailResult) 165 let emailSecurity = mapOptionalValueServiceResult(normalizedEmailResult)
295 let ptrRecord = mapOptionalServiceResult(ptrOutcome.map { normalizeErrors(in: $0.value) }, missingMessage: "No A record available") 166 let ptrRecord = mapOptionalServiceResult(ptrOutcome.map { normalizeErrors(in: $0.value) }, missingMessage: "No A record available")
296 let geolocation = mapOptionalServiceResult(geoOutcome.map { normalizeErrors(in: $0.value) }, missingMessage: "No A record available") 167 let geolocation = mapOptionalServiceResult(geoOutcome.map { normalizeErrors(in: $0.value) }, missingMessage: "No A record available")
297 let availabilityConfidence = confidenceForAvailability(result: availability.value, provenance: provenanceBySection[.availability]) 168 let availabilityConfidence = confidenceForAvailability(result: availability.value, provenance: ledger.provenanceBySection[.availability])
298 let ownershipConfidence = confidenceForOwnership(result: ownership.value) 169 let ownershipConfidence = confidenceForOwnership(result: ownership.value)
299 let subdomainConfidence = confidenceForSubdomains(results: subdomains.value) 170 let subdomainConfidence = confidenceForSubdomains(results: subdomains.value)
300 let emailConfidence = confidenceForEmail(result: emailSecurity.value) 171 let emailConfidence = confidenceForEmail(result: emailSecurity.value)
301 let geolocationConfidence = confidenceForGeolocation(result: geolocation.value) 172 let geolocationConfidence = confidenceForGeolocation(result: geolocation.value)
302 let validationIssues = validationIssues(for: normalizedDomain, snapshotTimestamp: startedAt, availability: availability.value, dnsSections: dnsSections.value, provenanceBySection: provenanceBySection) 173 let validationIssues = validationIssues(for: normalizedDomain, snapshotTimestamp: startedAt, availability: availability.value, dnsSections: dnsSections.value, provenanceBySection: ledger.provenanceBySection)
303 174
304 let snapshot = LookupSnapshot( 175 let snapshot = LookupSnapshot(
305 historyEntryID: nil, 176 historyEntryID: nil,
@@ -310,14 +181,14 @@ struct DomainInspectionService {
310 appVersion: AppVersion.current, 181 appVersion: AppVersion.current,
311 resolverDisplayName: resolverDisplayName, 182 resolverDisplayName: resolverDisplayName,
312 resolverURLString: resolverURLString, 183 resolverURLString: resolverURLString,
313 dataSources: Array(dataSources).sorted(), 184 dataSources: Array(ledger.dataSources).sorted(),
314 provenanceBySection: provenanceBySection, 185 provenanceBySection: ledger.provenanceBySection,
315 availabilityConfidence: availabilityConfidence, 186 availabilityConfidence: availabilityConfidence,
316 ownershipConfidence: ownershipConfidence, 187 ownershipConfidence: ownershipConfidence,
317 subdomainConfidence: subdomainConfidence, 188 subdomainConfidence: subdomainConfidence,
318 emailSecurityConfidence: emailConfidence, 189 emailSecurityConfidence: emailConfidence,
319 geolocationConfidence: geolocationConfidence, 190 geolocationConfidence: geolocationConfidence,
320 errorDetails: errorDetails, 191 errorDetails: ledger.errorDetails,
321 isPartialSnapshot: !validationIssues.isEmpty, 192 isPartialSnapshot: !validationIssues.isEmpty,
322 validationIssues: validationIssues, 193 validationIssues: validationIssues,
323 totalLookupDurationMs: Int(Date().timeIntervalSince(startedAt) * 1000), 194 totalLookupDurationMs: Int(Date().timeIntervalSince(startedAt) * 1000),
@@ -374,8 +245,8 @@ struct DomainInspectionService {
374 portScanResults: portScanResults.value, 245 portScanResults: portScanResults.value,
375 portScanError: portScanResults.message, 246 portScanError: portScanResults.message,
376 changeSummary: nil, 247 changeSummary: nil,
377 resultSource: aggregateSource(sectionSources), 248 resultSource: aggregateSource(ledger.sectionSources),
378 cachedSections: Array(cachedSections).sorted { $0.rawValue < $1.rawValue }, 249 cachedSections: Array(ledger.cachedSections).sorted { $0.rawValue < $1.rawValue },
379 statusMessage: nil 250 statusMessage: nil
380 ) 251 )
381 DomainDebugLog.signpostEnd( 252 DomainDebugLog.signpostEnd(
@@ -396,24 +267,36 @@ struct DomainInspectionService {
396 .lowercased() ?? domain.lowercased() 267 .lowercased() ?? domain.lowercased()
397 } 268 }
398 269
399 private func track( 270 /// A lookup that needs an address to reach, or an empty result when the
400 _ section: LookupSectionKind, 271 /// domain has none.
401 source: LookupResultSource, 272 private func whenRoutable<Value>(
402 provenance: SectionProvenance, 273 _ hasNetworkTarget: Bool,
403 cachedSections: inout Set<LookupSectionKind>, 274 fetch: () async -> CachedLookupResult<ServiceResult<Value>>
404 sectionSources: inout [LookupResultSource], 275 ) async -> CachedLookupResult<ServiceResult<Value>> {
405 provenanceBySection: inout [LookupSectionKind: SectionProvenance], 276 guard hasNetworkTarget else {
406 dataSources: inout Set<String> 277 return CachedLookupResult(value: .empty("No routable address available"), source: .live)
407 ) {
408 sectionSources.append(source)
409 provenanceBySection[section] = provenance
410 dataSources.insert(provenance.provider ?? provenance.source)
411 if source != .live {
412 cachedSections.insert(section)
413 } 278 }
279 return await fetch()
280 }
281
282 /// The previous snapshot's value, or its error, when its section can be
283 /// reused; otherwise a fresh lookup.
284 private func reusingPrevious<Value>(
285 _ value: Value?,
286 error: String?,
287 when reusable: Bool,
288 otherwise fetch: () async -> CachedLookupResult<ServiceResult<Value>>
289 ) async -> CachedLookupResult<ServiceResult<Value>> {
290 if reusable, let value {
291 return CachedLookupResult(value: .success(value), source: .cached)
292 }
293 if reusable, let error {
294 return CachedLookupResult(value: .error(error), source: .cached)
295 }
296 return await fetch()
414 } 297 }
415 298
416 private func provenance( 299 fileprivate static func provenance(
417 for section: LookupSectionKind, 300 for section: LookupSectionKind,
418 source: LookupResultSource, 301 source: LookupResultSource,
419 collectedAt: Date, 302 collectedAt: Date,
@@ -514,13 +397,13 @@ struct DomainInspectionService {
514 case let .success(value): 397 case let .success(value):
515 return .success(value) 398 return .success(value)
516 case let .empty(message): 399 case let .empty(message):
517 return .empty(classifyFailure(from: message, defaultKind: .unavailable).message) 400 return .empty(Self.classifyFailure(from: message, defaultKind: .unavailable).message)
518 case let .error(message): 401 case let .error(message):
519 return .error(classifyFailure(from: message).message) 402 return .error(Self.classifyFailure(from: message).message)
520 } 403 }
521 } 404 }
522 405
523 private func classifyFailure(from message: String, defaultKind: InspectionErrorKind = .unknown) -> InspectionFailure { 406 fileprivate static func classifyFailure(from message: String, defaultKind: InspectionErrorKind = .unknown) -> InspectionFailure {
524 let normalizedMessage = message.trimmingCharacters(in: .whitespacesAndNewlines) 407 let normalizedMessage = message.trimmingCharacters(in: .whitespacesAndNewlines)
525 let lowercasedMessage = normalizedMessage.lowercased() 408 let lowercasedMessage = normalizedMessage.lowercased()
526 if lowercasedMessage.contains("timed out") { 409 if lowercasedMessage.contains("timed out") {
@@ -554,21 +437,6 @@ struct DomainInspectionService {
554 return InspectionFailure(kind: .unknown, message: normalizedMessage.isEmpty ? defaultKind.title : normalizedMessage, details: normalizedMessage) 437 return InspectionFailure(kind: .unknown, message: normalizedMessage.isEmpty ? defaultKind.title : normalizedMessage, details: normalizedMessage)
555 } 438 }
556 439
557 private func captureFailure<Value>(
558 for section: LookupSectionKind,
559 result: ServiceResult<Value>,
560 into errorDetails: inout [LookupSectionKind: InspectionFailure]
561 ) {
562 switch result {
563 case .success:
564 return
565 case let .empty(message):
566 errorDetails[section] = classifyFailure(from: message, defaultKind: .unavailable)
567 case let .error(message):
568 errorDetails[section] = classifyFailure(from: message)
569 }
570 }
571
572 private func confidenceForAvailability(result: DomainAvailabilityResult, provenance: SectionProvenance?) -> ConfidenceLevel { 440 private func confidenceForAvailability(result: DomainAvailabilityResult, provenance: SectionProvenance?) -> ConfidenceLevel {
573 guard result.status != .unknown else { return .low } 441 guard result.status != .unknown else { return .low }
574 if provenance?.provider?.localizedCaseInsensitiveContains("rdap.org") == true, result.status == .registered { 442 if provenance?.provider?.localizedCaseInsensitiveContains("rdap.org") == true, result.status == .registered {
@@ -717,3 +585,40 @@ struct DomainInspectionService {
717 } 585 }
718 } 586 }
719} 587}
588
589/// What an inspection has learned about its sections so far: where each came
590/// from, which were served from cache, and which failed.
591private struct InspectionLedger {
592 let resolverDisplayName: String
593 var cachedSections = Set<LookupSectionKind>()
594 var sectionSources: [LookupResultSource] = []
595 var provenanceBySection: [LookupSectionKind: SectionProvenance] = [:]
596 var dataSources = Set<String>()
597 var errorDetails: [LookupSectionKind: InspectionFailure] = [:]
598
599 mutating func track(_ section: LookupSectionKind, source: LookupResultSource) {
600 let provenance = DomainInspectionService.provenance(
601 for: section,
602 source: source,
603 collectedAt: Date(),
604 resolverDisplayName: resolverDisplayName
605 )
606 sectionSources.append(source)
607 provenanceBySection[section] = provenance
608 dataSources.insert(provenance.provider ?? provenance.source)
609 if source != .live {
610 cachedSections.insert(section)
611 }
612 }
613
614 mutating func captureFailure<Value>(for section: LookupSectionKind, result: ServiceResult<Value>) {
615 switch result {
616 case .success:
617 return
618 case let .empty(message):
619 errorDetails[section] = DomainInspectionService.classifyFailure(from: message, defaultKind: .unavailable)
620 case let .error(message):
621 errorDetails[section] = DomainInspectionService.classifyFailure(from: message)
622 }
623 }
624}
LocalAPIService.swift +3 −30
@@ -303,47 +303,20 @@ final class LocalAPIService {
303 static let reference = "DomainDig.LocalAPI.Token" 303 static let reference = "DomainDig.LocalAPI.Token"
304 304
305 static func save(secret: String, reference: String) throws { 305 static func save(secret: String, reference: String) throws {
306 let data = Data(secret.utf8) 306 guard GenericPasswordKeychain.save(secret, reference: reference) else {
307 try? delete(reference: reference)
308
309 let query: [String: Any] = [
310 kSecClass as String: kSecClassGenericPassword,
311 kSecAttrAccount as String: reference,
312 kSecValueData as String: data,
313 kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock
314 ]
315
316 let status = SecItemAdd(query as CFDictionary, nil)
317 guard status == errSecSuccess else {
318 throw LocalAPIServerError.secretPersistenceFailed 307 throw LocalAPIServerError.secretPersistenceFailed
319 } 308 }
320 } 309 }
321 310
322 static func secret(reference: String) throws -> String { 311 static func secret(reference: String) throws -> String {
323 let query: [String: Any] = [ 312 guard let secret = GenericPasswordKeychain.secret(reference: reference) else {
324 kSecClass as String: kSecClassGenericPassword,
325 kSecAttrAccount as String: reference,
326 kSecReturnData as String: true,
327 kSecMatchLimit as String: kSecMatchLimitOne
328 ]
329
330 var result: CFTypeRef?
331 let status = SecItemCopyMatching(query as CFDictionary, &result)
332 guard status == errSecSuccess,
333 let data = result as? Data,
334 let secret = String(data: data, encoding: .utf8) else {
335 throw LocalAPIServerError.missingSecret 313 throw LocalAPIServerError.missingSecret
336 } 314 }
337
338 return secret 315 return secret
339 } 316 }
340 317
341 static func delete(reference: String) throws { 318 static func delete(reference: String) throws {
342 let query: [String: Any] = [ 319 GenericPasswordKeychain.delete(reference: reference)
343 kSecClass as String: kSecClassGenericPassword,
344 kSecAttrAccount as String: reference
345 ]
346 SecItemDelete(query as CFDictionary)
347 } 320 }
348 } 321 }
349 322