Commit e40c6d02e6

e40c6d02e656379e910a69697262114854c6f241

parent: 2accaa0ea7

Unsigned

cmc <hello@cleberg.net> · 2026-10-24 22:51 UTC

Move history into files plus an index (!26)

A1 under D3. History leaves the single `UserDefaults` blob for one JSON file
per snapshot plus an index.

Measured in !23: at the Pro+ cap of 2000 rows the blob is 6.4 MiB, 214 ms to
save and 209 ms to load, and `saveHistoryEntries` runs on the main actor after
every lookup. Ten consecutive saves cost 210 ms each — rewriting the whole blob
does not amortize.

## What the measurements decided

| operation at 2000 rows | blob | files |
|---|---|---|
| append one snapshot | 216 ms | **23 ms** |
| read what the list needs | 217 ms | **11 ms** (index) |
| rewrite every row | 207 ms | 656 ms |

The first shape of this change kept the existing whole-array API and was
**worse on every write** — 890 ms to append — because `replaceAll` had to read
all 2000 files to work out what changed. The whole-array signature gives it no
other way to know. So the writers say what they changed instead:
`appendHistoryEntry`, `updateHistoryEntry`, `removeHistoryEntries`. The full
rewrite is slower and is reserved for the cases that really do change every
row: the v2 migration, a backup import, an explicit prune.

In the view model each writer now names its mutation. `persistHistory` has one
caller left — the auto-prune setting, the only writer that drops rows from the
middle and cannot say which.

## The cap is the caller's business

`saveHistoryEntries` stores what it is given. An earlier draft had it enforce
250 and that is data loss: a backup import would quietly truncate a user's
history. Only `append` prunes, because only `append` adds the row that pushes
the oldest one off, and it takes the limit from the caller — the view model's
auto-prune choice, clamped to the store ceiling, as one expression so the
in-memory trim and the on-disk prune cannot drift.

## Migration and reset

v2 reads the blob, writes the files, and clears the key only once the files are
on disk, so an interrupted run retries from the blob. Safe on an empty store
and idempotent; both covered.

`DataResetService` clears the directory. History is no longer inside the
`UserDefaults` domain the wipe removes, so without this a reset would have left
the user's snapshots on the device.

## `historyLocation` is not defaulted through the core

Defaulting it hid five call sites that silently read and wrote the real store,
including `backupData`, which never passed it to `currentBackup` — so every
backup read history from the wrong directory. Removing the default found all
five at compile time. The headless callers that genuinely want the real store —
`MonitoringStorage`, the Local API's reads, the scheduled report run — say
`.default` explicitly.

Four test files needed their own scratch directory: a scratch `UserDefaults`
suite no longer keeps a test off the real store. That is the same lesson !21
learned for `defaults:`, and I reproduced it before fixing it.

## Verification

Both tiers from cold through `./Scripts/test.sh`: 225 tests, 0 failures on iOS
18.6 (iPhone 16) and iOS 27.0 (iPhone Air). Needs !24 and !25 — without them
this branch could not be run to completion at all.

Layout: unified · split

DomainDataPortabilityService.swift +196 −35
@@ -352,7 +352,7 @@ enum DataPortabilityCSV {
352/// The policy is documented in `Docs/data-migration.md`. 352/// The policy is documented in `Docs/data-migration.md`.
353enum DataMigrationService { 353enum DataMigrationService {
354 /// The schema version this build expects the on-device store to be at. 354 /// The schema version this build expects the on-device store to be at.
355 static let currentStoreSchemaVersion = 1 355 static let currentStoreSchemaVersion = 2
356 356
357 /// UserDefaults key holding the store's current schema version. 357 /// UserDefaults key holding the store's current schema version.
358 static let storeSchemaVersionKey = "data.storeSchemaVersion" 358 static let storeSchemaVersionKey = "data.storeSchemaVersion"
@@ -371,7 +371,10 @@ enum DataMigrationService {
371 return defaults.bool(forKey: legacyNormalizationMarkerKey) ? 1 : 0 371 return defaults.bool(forKey: legacyNormalizationMarkerKey) ? 1 : 0
372 } 372 }
373 373
374 static func migrateIfNeeded(defaults: UserDefaults = .standard) { 374 static func migrateIfNeeded(
375 defaults: UserDefaults = .standard,
376 historyLocation: HistoryFileStore.Location
377 ) {
375 // At or ahead of this build's version: nothing to do, and never rewrite 378 // At or ahead of this build's version: nothing to do, and never rewrite
376 // a store a newer build may have reshaped (forward compatibility). 379 // a store a newer build may have reshaped (forward compatibility).
377 guard storeSchemaVersion(defaults: defaults) < currentStoreSchemaVersion else { return } 380 guard storeSchemaVersion(defaults: defaults) < currentStoreSchemaVersion else { return }
@@ -379,31 +382,74 @@ enum DataMigrationService {
379 var version = storeSchemaVersion(defaults: defaults) 382 var version = storeSchemaVersion(defaults: defaults)
380 while version < currentStoreSchemaVersion { 383 while version < currentStoreSchemaVersion {
381 let target = version + 1 384 let target = version + 1
382 runMigration(to: target, defaults: defaults) 385 runMigration(to: target, defaults: defaults, historyLocation: historyLocation)
383 defaults.set(target, forKey: storeSchemaVersionKey) 386 defaults.set(target, forKey: storeSchemaVersionKey)
384 version = target 387 version = target
385 } 388 }
386 } 389 }
387 390
388 private static func runMigration(to version: Int, defaults: UserDefaults) { 391 private static func runMigration(
392 to version: Int,
393 defaults: UserDefaults,
394 historyLocation: HistoryFileStore.Location
395 ) {
389 switch version { 396 switch version {
390 case 1: 397 case 1:
391 normalizeAllStores(defaults: defaults) 398 normalizeAllStores(defaults: defaults, historyLocation: historyLocation)
399 case 2:
400 moveHistoryToFiles(defaults: defaults, historyLocation: historyLocation)
392 default: 401 default:
393 break 402 break
394 } 403 }
395 } 404 }
396 405
406 /// v2: history moves out of the `UserDefaults` blob into one file per
407 /// snapshot plus an index (A1 under D3). Reads the blob directly rather
408 /// than through `loadHistoryEntries`, which already prefers the files and
409 /// would return nothing here, and clears the key only once the files are
410 /// written. Safe on an empty store and on one a v2 build already moved.
411 private static func moveHistoryToFiles(
412 defaults: UserDefaults,
413 historyLocation: HistoryFileStore.Location
414 ) {
415 guard let data = defaults.data(forKey: DomainDataPortabilityService.legacyHistoryBlobKey) else { return }
416
417 let entries = (try? JSONDecoder().decode([HistoryEntry].self, from: data)) ?? []
418 guard !entries.isEmpty else {
419 defaults.removeObject(forKey: DomainDataPortabilityService.legacyHistoryBlobKey)
420 return
421 }
422
423 DomainDataPortabilityService.saveHistoryEntries(
424 entries,
425 defaults: defaults,
426 historyLocation: historyLocation
427 )
428
429 // `saveHistoryEntries` clears the key, but only after the files are on
430 // disk — so an interrupted migration leaves the blob to retry from.
431 }
432
397 /// v1: load every store through its deduplicating loader and write it back. 433 /// v1: load every store through its deduplicating loader and write it back.
398 /// This consolidates duplicate rows, drops the legacy `watchedDomains` key 434 /// This consolidates duplicate rows, drops the legacy `watchedDomains` key
399 /// (via `saveTrackedDomains`), and sanitizes monitoring settings against the 435 /// (via `saveTrackedDomains`), and sanitizes monitoring settings against the
400 /// surviving tracked domains. Safe on an empty store (every step is a no-op). 436 /// surviving tracked domains. Safe on an empty store (every step is a no-op).
401 private static func normalizeAllStores(defaults: UserDefaults) { 437 private static func normalizeAllStores(
438 defaults: UserDefaults,
439 historyLocation: HistoryFileStore.Location
440 ) {
402 let trackedDomains = DomainDataPortabilityService.loadTrackedDomains(defaults: defaults) 441 let trackedDomains = DomainDataPortabilityService.loadTrackedDomains(defaults: defaults)
403 DomainDataPortabilityService.saveTrackedDomains(trackedDomains, defaults: defaults) 442 DomainDataPortabilityService.saveTrackedDomains(trackedDomains, defaults: defaults)
404 443
405 let historyEntries = DomainDataPortabilityService.loadHistoryEntries(defaults: defaults) 444 let historyEntries = DomainDataPortabilityService.loadHistoryEntries(
406 DomainDataPortabilityService.saveHistoryEntries(historyEntries, defaults: defaults) 445 defaults: defaults,
446 historyLocation: historyLocation
447 )
448 DomainDataPortabilityService.saveHistoryEntries(
449 historyEntries,
450 defaults: defaults,
451 historyLocation: historyLocation
452 )
407 453
408 let auditSessions = DomainDataPortabilityService.loadAuditSessions(defaults: defaults) 454 let auditSessions = DomainDataPortabilityService.loadAuditSessions(defaults: defaults)
409 DomainDataPortabilityService.saveAuditSessions(auditSessions, defaults: defaults) 455 DomainDataPortabilityService.saveAuditSessions(auditSessions, defaults: defaults)
@@ -601,7 +647,19 @@ enum DomainDataPortabilityService {
601 defaults.removeObject(forKey: StorageKey.legacyWatchedDomains) 647 defaults.removeObject(forKey: StorageKey.legacyWatchedDomains)
602 } 648 }
603 649
604 static func loadHistoryEntries(defaults: UserDefaults = .standard) -> [HistoryEntry] { 650 /// Every snapshot, in full. The file store is the substrate (A1 under D3);
651 /// the `UserDefaults` branch below is only reached before the v2 migration
652 /// has run, and on a store the migration found empty.
653 ///
654 /// Callers that only list history should read `loadHistoryIndex` instead:
655 /// at the Pro+ cap of 2000 rows that is 11 ms against this path's 243 ms.
656 static func loadHistoryEntries(
657 defaults: UserDefaults = .standard,
658 historyLocation: HistoryFileStore.Location
659 ) -> [HistoryEntry] {
660 let fromFiles = HistoryFileStore.loadAllEntries(at: historyLocation)
661 if !fromFiles.isEmpty { return fromFiles }
662
605 guard let data = defaults.data(forKey: StorageKey.history) else { return [] } 663 guard let data = defaults.data(forKey: StorageKey.history) else { return [] }
606 664
607 if let entries = try? JSONDecoder().decode([HistoryEntry].self, from: data) { 665 if let entries = try? JSONDecoder().decode([HistoryEntry].self, from: data) {
@@ -623,12 +681,89 @@ enum DomainDataPortabilityService {
623 return deduplicatedHistoryEntries(entries) 681 return deduplicatedHistoryEntries(entries)
624 } 682 }
625 683
626 static func saveHistoryEntries(_ historyEntries: [HistoryEntry], defaults: UserDefaults = .standard) { 684 /// Rewrites the whole store. This is the migration, a backup import and an
627 if let data = try? JSONEncoder().encode(deduplicatedHistoryEntries(historyEntries)) { 685 /// explicit prune — the cases that really do change every row. A single new
628 defaults.set(data, forKey: StorageKey.history) 686 /// snapshot should go through `appendHistoryEntry`, which costs 23 ms at
629 } 687 /// the Pro+ cap against this path's 656 ms.
688 static func saveHistoryEntries(
689 _ historyEntries: [HistoryEntry],
690 defaults: UserDefaults = .standard,
691 historyLocation: HistoryFileStore.Location
692 ) {
693 // Stores what it is given. The retention cap is the caller's business:
694 // a backup import, an export round trip and the v2 migration must not
695 // silently drop rows the user still has.
696 HistoryFileStore.replaceAll(
697 with: deduplicatedHistoryEntries(historyEntries),
698 cap: Int.max,
699 at: historyLocation
700 )
701 defaults.removeObject(forKey: StorageKey.history)
702 }
703
704 /// The index alone: what the history list, its filters and its sorts read.
705 static func loadHistoryIndex(
706 defaults: UserDefaults = .standard,
707 historyLocation: HistoryFileStore.Location
708 ) -> [HistoryIndexRow] {
709 HistoryFileStore.loadIndex(at: historyLocation)
710 }
711
712 static func loadHistoryEntry(
713 id: UUID,
714 defaults: UserDefaults = .standard,
715 historyLocation: HistoryFileStore.Location
716 ) -> HistoryEntry? {
717 HistoryFileStore.loadEntry(id: id, at: historyLocation)
718 }
719
720 /// `cap` is the caller's effective retention limit. Append is the only
721 /// writer that prunes, because it is the only one that adds a row: the
722 /// snapshot that falls off the end has to be deleted from disk by someone,
723 /// and the in-memory array the view model trims cannot do it.
724 static func appendHistoryEntry(
725 _ entry: HistoryEntry,
726 cap: Int,
727 defaults: UserDefaults = .standard,
728 historyLocation: HistoryFileStore.Location
729 ) {
730 HistoryFileStore.append(entry, cap: cap, at: historyLocation)
630 } 731 }
631 732
733 static func updateHistoryEntry(
734 _ entry: HistoryEntry,
735 defaults: UserDefaults = .standard,
736 historyLocation: HistoryFileStore.Location
737 ) {
738 HistoryFileStore.update(entry, at: historyLocation)
739 }
740
741 static func removeHistoryEntries(
742 ids: Set<UUID>,
743 defaults: UserDefaults = .standard,
744 historyLocation: HistoryFileStore.Location
745 ) {
746 HistoryFileStore.remove(ids: ids, at: historyLocation)
747 }
748
749 static func removeAllHistoryEntries(
750 defaults: UserDefaults = .standard,
751 historyLocation: HistoryFileStore.Location
752 ) {
753 HistoryFileStore.removeAll(at: historyLocation)
754 defaults.removeObject(forKey: StorageKey.history)
755 }
756
757 /// The key history occupied before v2 moved it into files. The migration
758 /// reads it; nothing else should.
759 static let legacyHistoryBlobKey = StorageKey.history
760
761 /// The hard ceiling on history, independent of the user's auto-prune
762 /// setting. The per-tier retention dial D1 settled on (50/250/2000)
763 /// replaces this constant; until then every tier shares it.
764 static let historyStorageCap = 250
765
766
632 static func loadAuditSessions(defaults: UserDefaults = .standard) -> [AuditSession] { 767 static func loadAuditSessions(defaults: UserDefaults = .standard) -> [AuditSession] {
633 guard let data = defaults.data(forKey: StorageKey.audits), 768 guard let data = defaults.data(forKey: StorageKey.audits),
634 let sessions = try? JSONDecoder().decode([AuditSession].self, from: data) else { 769 let sessions = try? JSONDecoder().decode([AuditSession].self, from: data) else {
@@ -719,14 +854,17 @@ enum DomainDataPortabilityService {
719 } 854 }
720 } 855 }
721 856
722 static func currentBackup(defaults: UserDefaults = .standard) -> DomainDigBackup { 857 static func currentBackup(
723 DataMigrationService.migrateIfNeeded(defaults: defaults) 858 defaults: UserDefaults = .standard,
859 historyLocation: HistoryFileStore.Location
860 ) -> DomainDigBackup {
861 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
724 return DomainDigBackup( 862 return DomainDigBackup(
725 schemaVersion: DomainDigBackup.currentSchemaVersion, 863 schemaVersion: DomainDigBackup.currentSchemaVersion,
726 exportedAt: Date(), 864 exportedAt: Date(),
727 appVersion: AppVersion.current, 865 appVersion: AppVersion.current,
728 trackedDomains: loadTrackedDomains(defaults: defaults), 866 trackedDomains: loadTrackedDomains(defaults: defaults),
729 historyEntries: loadHistoryEntries(defaults: defaults), 867 historyEntries: loadHistoryEntries(defaults: defaults, historyLocation: historyLocation),
730 auditSessions: loadAuditSessions(defaults: defaults), 868 auditSessions: loadAuditSessions(defaults: defaults),
731 workflows: loadWorkflows(defaults: defaults), 869 workflows: loadWorkflows(defaults: defaults),
732 monitoringSettings: loadMonitoringSettings(defaults: defaults), 870 monitoringSettings: loadMonitoringSettings(defaults: defaults),
@@ -736,8 +874,11 @@ enum DomainDataPortabilityService {
736 ) 874 )
737 } 875 }
738 876
739 static func backupData(defaults: UserDefaults = .standard) throws -> Data { 877 static func backupData(
740 try makeEncoder().encode(currentBackup(defaults: defaults)) 878 defaults: UserDefaults = .standard,
879 historyLocation: HistoryFileStore.Location
880 ) throws -> Data {
881 try makeEncoder().encode(currentBackup(defaults: defaults, historyLocation: historyLocation))
741 } 882 }
742 883
743 static func trackedDomainsExportData(defaults: UserDefaults = .standard) throws -> Data { 884 static func trackedDomainsExportData(defaults: UserDefaults = .standard) throws -> Data {
@@ -762,13 +903,16 @@ enum DomainDataPortabilityService {
762 ) 903 )
763 } 904 }
764 905
765 static func historyExportData(defaults: UserDefaults = .standard) throws -> Data { 906 static func historyExportData(
907 defaults: UserDefaults = .standard,
908 historyLocation: HistoryFileStore.Location
909 ) throws -> Data {
766 try makeEncoder().encode( 910 try makeEncoder().encode(
767 HistoryExport( 911 HistoryExport(
768 schemaVersion: DomainDigBackup.currentSchemaVersion, 912 schemaVersion: DomainDigBackup.currentSchemaVersion,
769 exportedAt: Date(), 913 exportedAt: Date(),
770 appVersion: AppVersion.current, 914 appVersion: AppVersion.current,
771 historyEntries: loadHistoryEntries(defaults: defaults) 915 historyEntries: loadHistoryEntries(defaults: defaults, historyLocation: historyLocation)
772 ) 916 )
773 ) 917 )
774 } 918 }
@@ -785,13 +929,19 @@ enum DomainDataPortabilityService {
785 data: Data, 929 data: Data,
786 fileName: String, 930 fileName: String,
787 mode: DataPortabilityImportMode, 931 mode: DataPortabilityImportMode,
788 defaults: UserDefaults = .standard 932 defaults: UserDefaults = .standard,
933 historyLocation: HistoryFileStore.Location
789 ) throws -> DataImportPreview { 934 ) throws -> DataImportPreview {
790 DataMigrationService.migrateIfNeeded(defaults: defaults) 935 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
791 let currentCounts = lifecycleSummary(defaults: defaults) 936 let currentCounts = lifecycleSummary(defaults: defaults, historyLocation: historyLocation)
792 937
793 let payload = try decodeImportPayload(from: data, fileName: fileName) 938 let payload = try decodeImportPayload(from: data, fileName: fileName)
794 let projectedCounts = projectCounts(for: payload, mode: mode, defaults: defaults) 939 let projectedCounts = projectCounts(
940 for: payload,
941 mode: mode,
942 defaults: defaults,
943 historyLocation: historyLocation
944 )
795 945
796 return DataImportPreview( 946 return DataImportPreview(
797 fileName: fileName, 947 fileName: fileName,
@@ -808,11 +958,12 @@ enum DomainDataPortabilityService {
808 static func applyImport( 958 static func applyImport(
809 _ preview: DataImportPreview, 959 _ preview: DataImportPreview,
810 mode: DataPortabilityImportMode, 960 mode: DataPortabilityImportMode,
811 defaults: UserDefaults = .standard 961 defaults: UserDefaults = .standard,
962 historyLocation: HistoryFileStore.Location
812 ) throws -> DataImportResult { 963 ) throws -> DataImportResult {
813 switch preview.payload { 964 switch preview.payload {
814 case .backup(let backup, let report): 965 case .backup(let backup, let report):
815 try applyBackup(backup, mode: mode, defaults: defaults) 966 try applyBackup(backup, mode: mode, defaults: defaults, historyLocation: historyLocation)
816 return DataImportResult( 967 return DataImportResult(
817 kind: .backup, 968 kind: .backup,
818 mode: mode, 969 mode: mode,
@@ -849,7 +1000,10 @@ enum DomainDataPortabilityService {
849 } 1000 }
850 } 1001 }
851 1002
852 static func lifecycleSummary(defaults: UserDefaults = .standard) -> DataLifecycleSummary { 1003 static func lifecycleSummary(
1004 defaults: UserDefaults = .standard,
1005 historyLocation: HistoryFileStore.Location
1006 ) -> DataLifecycleSummary {
853 let appSettings = loadAppSettings(defaults: defaults) 1007 let appSettings = loadAppSettings(defaults: defaults)
854 let featureMetadata = loadFeatureMetadata(defaults: defaults) 1008 let featureMetadata = loadFeatureMetadata(defaults: defaults)
855 let cachedItems = appSettings.recentSearches.count 1009 let cachedItems = appSettings.recentSearches.count
@@ -857,7 +1011,7 @@ enum DomainDataPortabilityService {
857 1011
858 return DataLifecycleSummary( 1012 return DataLifecycleSummary(
859 trackedDomains: loadTrackedDomains(defaults: defaults).count, 1013 trackedDomains: loadTrackedDomains(defaults: defaults).count,
860 historySnapshots: loadHistoryEntries(defaults: defaults).count, 1014 historySnapshots: loadHistoryEntries(defaults: defaults, historyLocation: historyLocation).count,
861 auditSessions: loadAuditSessions(defaults: defaults).count, 1015 auditSessions: loadAuditSessions(defaults: defaults).count,
862 workflows: loadWorkflows(defaults: defaults).count, 1016 workflows: loadWorkflows(defaults: defaults).count,
863 cachedItems: cachedItems, 1017 cachedItems: cachedItems,
@@ -955,11 +1109,16 @@ enum DomainDataPortabilityService {
955 private static func applyBackup( 1109 private static func applyBackup(
956 _ backup: DomainDigBackup, 1110 _ backup: DomainDigBackup,
957 mode: DataPortabilityImportMode, 1111 mode: DataPortabilityImportMode,
958 defaults: UserDefaults 1112 defaults: UserDefaults,
1113 historyLocation: HistoryFileStore.Location
959 ) throws { 1114 ) throws {
960 if mode == .replace { 1115 if mode == .replace {
961 saveTrackedDomains(deduplicatedTrackedDomains(backup.trackedDomains), defaults: defaults) 1116 saveTrackedDomains(deduplicatedTrackedDomains(backup.trackedDomains), defaults: defaults)
962 saveHistoryEntries(deduplicatedHistoryEntries(backup.historyEntries), defaults: defaults) 1117 saveHistoryEntries(
1118 deduplicatedHistoryEntries(backup.historyEntries),
1119 defaults: defaults,
1120 historyLocation: historyLocation
1121 )
963 saveAuditSessions(backup.auditSessions ?? [], defaults: defaults) 1122 saveAuditSessions(backup.auditSessions ?? [], defaults: defaults)
964 saveWorkflows(deduplicatedWorkflows(backup.workflows), defaults: defaults) 1123 saveWorkflows(deduplicatedWorkflows(backup.workflows), defaults: defaults)
965 saveMonitoringSettings( 1124 saveMonitoringSettings(
@@ -979,11 +1138,12 @@ enum DomainDataPortabilityService {
979 let mergedTrackedDomains = mergeTrackedDomains(existing: existingTrackedDomains, incoming: backup.trackedDomains) 1138 let mergedTrackedDomains = mergeTrackedDomains(existing: existingTrackedDomains, incoming: backup.trackedDomains)
980 saveTrackedDomains(mergedTrackedDomains.domains, defaults: defaults) 1139 saveTrackedDomains(mergedTrackedDomains.domains, defaults: defaults)
981 1140
982 let existingHistoryEntries = loadHistoryEntries(defaults: defaults) 1141 let existingHistoryEntries = loadHistoryEntries(defaults: defaults, historyLocation: historyLocation)
983 let remappedIncomingHistory = backup.historyEntries.map { remapHistoryEntry($0, using: mergedTrackedDomains.idMap) } 1142 let remappedIncomingHistory = backup.historyEntries.map { remapHistoryEntry($0, using: mergedTrackedDomains.idMap) }
984 saveHistoryEntries( 1143 saveHistoryEntries(
985 mergeHistoryEntries(existing: existingHistoryEntries, incoming: remappedIncomingHistory), 1144 mergeHistoryEntries(existing: existingHistoryEntries, incoming: remappedIncomingHistory),
986 defaults: defaults 1145 defaults: defaults,
1146 historyLocation: historyLocation
987 ) 1147 )
988 1148
989 let existingAuditSessions = loadAuditSessions(defaults: defaults) 1149 let existingAuditSessions = loadAuditSessions(defaults: defaults)
@@ -1050,9 +1210,10 @@ enum DomainDataPortabilityService {
1050 private static func projectCounts( 1210 private static func projectCounts(
1051 for payload: ImportPayload, 1211 for payload: ImportPayload,
1052 mode: DataPortabilityImportMode, 1212 mode: DataPortabilityImportMode,
1053 defaults: UserDefaults 1213 defaults: UserDefaults,
1214 historyLocation: HistoryFileStore.Location
1054 ) -> DataLifecycleSummary { 1215 ) -> DataLifecycleSummary {
1055 let current = lifecycleSummary(defaults: defaults) 1216 let current = lifecycleSummary(defaults: defaults, historyLocation: historyLocation)
1056 switch payload { 1217 switch payload {
1057 case .backup(let backup, _): 1218 case .backup(let backup, _):
1058 if mode == .replace { 1219 if mode == .replace {
@@ -1068,7 +1229,7 @@ enum DomainDataPortabilityService {
1068 1229
1069 return DataLifecycleSummary( 1230 return DataLifecycleSummary(
1070 trackedDomains: mergeTrackedDomains(existing: loadTrackedDomains(defaults: defaults), incoming: backup.trackedDomains).domains.count, 1231 trackedDomains: mergeTrackedDomains(existing: loadTrackedDomains(defaults: defaults), incoming: backup.trackedDomains).domains.count,
1071 historySnapshots: mergeHistoryEntries(existing: loadHistoryEntries(defaults: defaults), incoming: backup.historyEntries).count, 1232 historySnapshots: mergeHistoryEntries(existing: loadHistoryEntries(defaults: defaults, historyLocation: historyLocation), incoming: backup.historyEntries).count,
1072 auditSessions: mergeAuditSessions(existing: loadAuditSessions(defaults: defaults), incoming: backup.auditSessions ?? []).count, 1233 auditSessions: mergeAuditSessions(existing: loadAuditSessions(defaults: defaults), incoming: backup.auditSessions ?? []).count,
1073 workflows: mergeWorkflows(existing: loadWorkflows(defaults: defaults), incoming: backup.workflows).count, 1234 workflows: mergeWorkflows(existing: loadWorkflows(defaults: defaults), incoming: backup.workflows).count,
1074 cachedItems: max(current.cachedItems, backup.appSettings.recentSearches.count), 1235 cachedItems: max(current.cachedItems, backup.appSettings.recentSearches.count),
DomainDig/DataResetService.swift +6
@@ -47,6 +47,12 @@ enum DataResetService {
47 47
48 try removeTemporaryFiles() 48 try removeTemporaryFiles()
49 49
50 // History is a directory in Application Support since the v2 store
51 // migration, so clearing the `UserDefaults` domain no longer reaches
52 // it. A reset that left it behind would leave the user's snapshots on
53 // the device after they asked for everything to go.
54 HistoryFileStore.removeAll()
55
50 let defaults = UserDefaults.standard 56 let defaults = UserDefaults.standard
51 defaults.removePersistentDomain(forName: bundleIdentifier) 57 defaults.removePersistentDomain(forName: bundleIdentifier)
52 defaults.synchronize() 58 defaults.synchronize()
DomainDig/DomainMonitoringService.swift +20 −8
@@ -18,7 +18,7 @@ enum MonitoringStorage {
18 static let maxLogs = 40 18 static let maxLogs = 40
19 19
20 static func loadSettings(defaults: UserDefaults = .standard) -> MonitoringSettings { 20 static func loadSettings(defaults: UserDefaults = .standard) -> MonitoringSettings {
21 DataMigrationService.migrateIfNeeded(defaults: defaults) 21 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: .default)
22 return DomainDataPortabilityService.loadMonitoringSettings(defaults: defaults) 22 return DomainDataPortabilityService.loadMonitoringSettings(defaults: defaults)
23 } 23 }
24 24
@@ -27,7 +27,7 @@ enum MonitoringStorage {
27 } 27 }
28 28
29 static func loadLogs(defaults: UserDefaults = .standard) -> [MonitoringLog] { 29 static func loadLogs(defaults: UserDefaults = .standard) -> [MonitoringLog] {
30 DataMigrationService.migrateIfNeeded(defaults: defaults) 30 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: .default)
31 return DomainDataPortabilityService.loadMonitoringLogs(defaults: defaults) 31 return DomainDataPortabilityService.loadMonitoringLogs(defaults: defaults)
32 } 32 }
33 33
@@ -36,7 +36,7 @@ enum MonitoringStorage {
36 } 36 }
37 37
38 static func loadTrackedDomains(defaults: UserDefaults = .standard) -> [TrackedDomain] { 38 static func loadTrackedDomains(defaults: UserDefaults = .standard) -> [TrackedDomain] {
39 DataMigrationService.migrateIfNeeded(defaults: defaults) 39 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: .default)
40 return DomainDataPortabilityService.loadTrackedDomains(defaults: defaults) 40 return DomainDataPortabilityService.loadTrackedDomains(defaults: defaults)
41 } 41 }
42 42
@@ -44,13 +44,25 @@ enum MonitoringStorage {
44 DomainDataPortabilityService.saveTrackedDomains(domains, defaults: defaults) 44 DomainDataPortabilityService.saveTrackedDomains(domains, defaults: defaults)
45 } 45 }
46 46
47 static func loadHistoryEntries(defaults: UserDefaults = .standard) -> [HistoryEntry] { 47 /// The background monitoring run has no view model, so the real store is
48 DataMigrationService.migrateIfNeeded(defaults: defaults) 48 /// the right one here. Stated rather than defaulted: every other history
49 return DomainDataPortabilityService.loadHistoryEntries(defaults: defaults) 49 /// caller names its directory.
50 static func loadHistoryEntries(
51 defaults: UserDefaults = .standard,
52 historyLocation: HistoryFileStore.Location = .default
53 ) -> [HistoryEntry] {
54 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
55 return DomainDataPortabilityService.loadHistoryEntries(
56 defaults: defaults,
57 historyLocation: historyLocation
58 )
50 } 59 }
51 60
52 static func saveHistoryEntries(_ entries: [HistoryEntry]) { 61 static func saveHistoryEntries(
53 DomainDataPortabilityService.saveHistoryEntries(entries) 62 _ entries: [HistoryEntry],
63 historyLocation: HistoryFileStore.Location = .default
64 ) {
65 DomainDataPortabilityService.saveHistoryEntries(entries, historyLocation: historyLocation)
54 } 66 }
55 67
56 static func sanitizeSettings(_ settings: MonitoringSettings, trackedDomains: [TrackedDomain]) -> MonitoringSettings { 68 static func sanitizeSettings(_ settings: MonitoringSettings, trackedDomains: [TrackedDomain]) -> MonitoringSettings {
DomainDig/DomainViewModel+Export.swift +15 −4
@@ -59,7 +59,7 @@ extension DomainViewModel {
59 } 59 }
60 60
61 func exportFullBackupData() -> Data? { 61 func exportFullBackupData() -> Data? {
62 try? DomainDataPortabilityService.backupData(defaults: defaults) 62 try? DomainDataPortabilityService.backupData(defaults: defaults, historyLocation: historyLocation)
63 } 63 }
64 64
65 func exportPortableTrackedDomainsJSONData() -> Data? { 65 func exportPortableTrackedDomainsJSONData() -> Data? {
@@ -79,7 +79,7 @@ extension DomainViewModel {
79 } 79 }
80 80
81 func exportPortableHistoryJSONData() -> Data? { 81 func exportPortableHistoryJSONData() -> Data? {
82 try? DomainDataPortabilityService.historyExportData(defaults: defaults) 82 try? DomainDataPortabilityService.historyExportData(defaults: defaults, historyLocation: historyLocation)
83 } 83 }
84 84
85 func prepareDataImport( 85 func prepareDataImport(
@@ -87,11 +87,22 @@ extension DomainViewModel {
87 fileName: String, 87 fileName: String,
88 mode: DataPortabilityImportMode 88 mode: DataPortabilityImportMode
89 ) throws -> DataImportPreview { 89 ) throws -> DataImportPreview {
90 try DomainDataPortabilityService.prepareImport(data: data, fileName: fileName, mode: mode, defaults: defaults) 90 try DomainDataPortabilityService.prepareImport(
91 data: data,
92 fileName: fileName,
93 mode: mode,
94 defaults: defaults,
95 historyLocation: historyLocation
96 )
91 } 97 }
92 98
93 func applyDataImport(_ preview: DataImportPreview, mode: DataPortabilityImportMode) throws -> DataImportResult { 99 func applyDataImport(_ preview: DataImportPreview, mode: DataPortabilityImportMode) throws -> DataImportResult {
94 let result = try DomainDataPortabilityService.applyImport(preview, mode: mode, defaults: defaults) 100 let result = try DomainDataPortabilityService.applyImport(
101 preview,
102 mode: mode,
103 defaults: defaults,
104 historyLocation: historyLocation
105 )
95 refreshPersistedData() 106 refreshPersistedData()
96 portabilityStatusMessage = result.summary 107 portabilityStatusMessage = result.summary
97 CloudSyncService.shared.markAppSettingsChanged() 108 CloudSyncService.shared.markAppSettingsChanged()
DomainDig/DomainViewModel+Workflows.swift +1 −1
@@ -132,7 +132,7 @@ extension DomainViewModel {
132 } 132 }
133 133
134 func refreshWorkflowList() async { 134 func refreshWorkflowList() async {
135 workflows = Self.loadWorkflows(defaults: defaults) 135 workflows = Self.loadWorkflows(defaults: defaults, historyLocation: historyLocation)
136 await Task.yield() 136 await Task.yield()
137 } 137 }
138} 138}
DomainDig/DomainViewModel.swift +112 −36
@@ -342,17 +342,25 @@ final class DomainViewModel {
342 /// one the app is using. 342 /// one the app is using.
343 let defaults: UserDefaults 343 let defaults: UserDefaults
344 344
345 init(defaults: UserDefaults = .standard) { 345 /// History lives in files rather than in `defaults`, so the directory is
346 /// injected alongside the store it used to be part of.
347 let historyLocation: HistoryFileStore.Location
348
349 init(
350 defaults: UserDefaults = .standard,
351 historyLocation: HistoryFileStore.Location = .default
352 ) {
346 self.defaults = defaults 353 self.defaults = defaults
354 self.historyLocation = historyLocation
347 recentSearches = DomainDataPortabilityService.loadRecentSearches(defaults: defaults) 355 recentSearches = DomainDataPortabilityService.loadRecentSearches(defaults: defaults)
348 trackedDomains = DomainViewModel.loadTrackedDomains(defaults: defaults) 356 trackedDomains = DomainViewModel.loadTrackedDomains(defaults: defaults, historyLocation: historyLocation)
349 history = DomainViewModel.loadHistoryEntries(defaults: defaults) 357 history = DomainViewModel.loadHistoryEntries(defaults: defaults, historyLocation: historyLocation)
350 auditSessions = DomainDataPortabilityService.loadAuditSessions(defaults: defaults) 358 auditSessions = DomainDataPortabilityService.loadAuditSessions(defaults: defaults)
351 workflows = DomainViewModel.loadWorkflows(defaults: defaults) 359 workflows = DomainViewModel.loadWorkflows(defaults: defaults, historyLocation: historyLocation)
352 watchlistSavedViews = DomainViewModel.loadWatchlistSavedViews(defaults: defaults) 360 watchlistSavedViews = DomainViewModel.loadWatchlistSavedViews(defaults: defaults)
353 monitoringSettings = MonitoringStorage.loadSettings(defaults: defaults) 361 monitoringSettings = MonitoringStorage.loadSettings(defaults: defaults)
354 monitoringLogs = MonitoringStorage.loadLogs(defaults: defaults) 362 monitoringLogs = MonitoringStorage.loadLogs(defaults: defaults)
355 dataLifecycleSummary = DomainDataPortabilityService.lifecycleSummary(defaults: defaults) 363 dataLifecycleSummary = DomainDataPortabilityService.lifecycleSummary(defaults: defaults, historyLocation: historyLocation)
356 historyAutoPruneOption = DomainViewModel.loadHistoryAutoPruneOption(defaults: defaults) 364 historyAutoPruneOption = DomainViewModel.loadHistoryAutoPruneOption(defaults: defaults)
357 } 365 }
358 366
@@ -843,13 +851,15 @@ final class DomainViewModel {
843 let ids = removedDomains.map(\.id) 851 let ids = removedDomains.map(\.id)
844 CloudSyncService.shared.recordTrackedDomainReset(removedDomains) 852 CloudSyncService.shared.recordTrackedDomainReset(removedDomains)
845 trackedDomains.removeAll { ids.contains($0.id) } 853 trackedDomains.removeAll { ids.contains($0.id) }
854 var relinked: [HistoryEntry] = []
846 history.indices.forEach { index in 855 history.indices.forEach { index in
847 if let trackedDomainID = history[index].trackedDomainID, ids.contains(trackedDomainID) { 856 if let trackedDomainID = history[index].trackedDomainID, ids.contains(trackedDomainID) {
848 history[index].trackedDomainID = nil 857 history[index].trackedDomainID = nil
858 relinked.append(history[index])
849 } 859 }
850 } 860 }
851 persistTrackedDomains() 861 persistTrackedDomains()
852 persistHistory() 862 relinked.forEach { storeHistoryEntry($0, replacingExisting: true) }
853 sanitizeMonitoringSelection() 863 sanitizeMonitoringSelection()
854 } 864 }
855 865
@@ -857,13 +867,15 @@ final class DomainViewModel {
857 guard canDelete(trackedDomain) else { return } 867 guard canDelete(trackedDomain) else { return }
858 CloudSyncService.shared.recordTrackedDomainDeletion(trackedDomain) 868 CloudSyncService.shared.recordTrackedDomainDeletion(trackedDomain)
859 trackedDomains.removeAll { $0.id == trackedDomain.id } 869 trackedDomains.removeAll { $0.id == trackedDomain.id }
870 var relinked: [HistoryEntry] = []
860 history.indices.forEach { index in 871 history.indices.forEach { index in
861 if history[index].trackedDomainID == trackedDomain.id { 872 if history[index].trackedDomainID == trackedDomain.id {
862 history[index].trackedDomainID = nil 873 history[index].trackedDomainID = nil
874 relinked.append(history[index])
863 } 875 }
864 } 876 }
865 persistTrackedDomains() 877 persistTrackedDomains()
866 persistHistory() 878 relinked.forEach { storeHistoryEntry($0, replacingExisting: true) }
867 sanitizeMonitoringSelection() 879 sanitizeMonitoringSelection()
868 } 880 }
869 881
@@ -948,18 +960,23 @@ final class DomainViewModel {
948 } 960 }
949 961
950 func removeHistoryEntries(at offsets: IndexSet) { 962 func removeHistoryEntries(at offsets: IndexSet) {
963 let removed = Set(offsets.map { history[$0].id })
951 history.remove(atOffsets: offsets) 964 history.remove(atOffsets: offsets)
952 persistHistory() 965 removeStoredHistory(ids: removed)
953 } 966 }
954 967
955 func removeHistoryEntries(withIDs ids: [UUID]) { 968 func removeHistoryEntries(withIDs ids: [UUID]) {
956 history.removeAll { ids.contains($0.id) } 969 history.removeAll { ids.contains($0.id) }
957 persistHistory() 970 removeStoredHistory(ids: Set(ids))
958 } 971 }
959 972
960 func clearHistory() { 973 func clearHistory() {
961 history.removeAll() 974 history.removeAll()
962 persistHistory() 975 DomainDataPortabilityService.removeAllHistoryEntries(
976 defaults: defaults,
977 historyLocation: historyLocation
978 )
979 refreshDataLifecycleSummary()
963 clearMonitoringLogs() 980 clearMonitoringLogs()
964 refreshDataLifecycleSummary() 981 refreshDataLifecycleSummary()
965 } 982 }
@@ -1001,9 +1018,9 @@ final class DomainViewModel {
1001 // scene activation); the disk reload below would wipe the fixtures. 1018 // scene activation); the disk reload below would wipe the fixtures.
1002 if auditFixturesActive { return } 1019 if auditFixturesActive { return }
1003 #endif 1020 #endif
1004 DataMigrationService.migrateIfNeeded(defaults: defaults) 1021 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
1005 trackedDomains = Self.loadTrackedDomains(defaults: defaults) 1022 trackedDomains = Self.loadTrackedDomains(defaults: defaults, historyLocation: historyLocation)
1006 history = Self.loadHistoryEntries(defaults: defaults) 1023 history = Self.loadHistoryEntries(defaults: defaults, historyLocation: historyLocation)
1007 monitoringSettings = MonitoringStorage.sanitizeSettings( 1024 monitoringSettings = MonitoringStorage.sanitizeSettings(
1008 MonitoringStorage.loadSettings(defaults: defaults), 1025 MonitoringStorage.loadSettings(defaults: defaults),
1009 trackedDomains: trackedDomains 1026 trackedDomains: trackedDomains
@@ -1014,7 +1031,7 @@ final class DomainViewModel {
1014 } 1031 }
1015 1032
1016 func refreshDataLifecycleSummary() { 1033 func refreshDataLifecycleSummary() {
1017 dataLifecycleSummary = DomainDataPortabilityService.lifecycleSummary(defaults: defaults) 1034 dataLifecycleSummary = DomainDataPortabilityService.lifecycleSummary(defaults: defaults, historyLocation: historyLocation)
1018 } 1035 }
1019 1036
1020 func refreshPersistedData() { 1037 func refreshPersistedData() {
@@ -1023,10 +1040,10 @@ final class DomainViewModel {
1023 if auditFixturesActive { return } 1040 if auditFixturesActive { return }
1024 #endif 1041 #endif
1025 recentSearches = DomainDataPortabilityService.loadRecentSearches(defaults: defaults) 1042 recentSearches = DomainDataPortabilityService.loadRecentSearches(defaults: defaults)
1026 trackedDomains = Self.loadTrackedDomains(defaults: defaults) 1043 trackedDomains = Self.loadTrackedDomains(defaults: defaults, historyLocation: historyLocation)
1027 history = Self.loadHistoryEntries(defaults: defaults) 1044 history = Self.loadHistoryEntries(defaults: defaults, historyLocation: historyLocation)
1028 auditSessions = DomainDataPortabilityService.loadAuditSessions(defaults: defaults) 1045 auditSessions = DomainDataPortabilityService.loadAuditSessions(defaults: defaults)
1029 workflows = Self.loadWorkflows(defaults: defaults) 1046 workflows = Self.loadWorkflows(defaults: defaults, historyLocation: historyLocation)
1030 monitoringSettings = MonitoringStorage.sanitizeSettings( 1047 monitoringSettings = MonitoringStorage.sanitizeSettings(
1031 MonitoringStorage.loadSettings(defaults: defaults), 1048 MonitoringStorage.loadSettings(defaults: defaults),
1032 trackedDomains: trackedDomains 1049 trackedDomains: trackedDomains
@@ -1792,7 +1809,10 @@ final class DomainViewModel {
1792 currentHistoryEntryID = entry.id 1809 currentHistoryEntryID = entry.id
1793 } 1810 }
1794 1811
1795 if replaceLatest, !history.isEmpty, history[0].domain.caseInsensitiveCompare(snapshot.domain) == .orderedSame { 1812 let replacedLatest = replaceLatest
1813 && !history.isEmpty
1814 && history[0].domain.caseInsensitiveCompare(snapshot.domain) == .orderedSame
1815 if replacedLatest {
1796 history[0] = entry 1816 history[0] = entry
1797 } else { 1817 } else {
1798 history.insert(entry, at: 0) 1818 history.insert(entry, at: 0)
@@ -1809,18 +1829,59 @@ final class DomainViewModel {
1809 certificateWarningLevel: DomainDiffService.certificateWarningLevel(for: snapshot), 1829 certificateWarningLevel: DomainDiffService.certificateWarningLevel(for: snapshot),
1810 certificateDaysRemaining: snapshot.sslInfo?.daysUntilExpiry 1830 certificateDaysRemaining: snapshot.sslInfo?.daysUntilExpiry
1811 ) 1831 )
1812 persistHistory() 1832 storeHistoryEntry(entry, replacingExisting: replacedLatest)
1813 notifyIfNeeded(for: entry, snapshot: snapshot, previousSnapshot: previousSnapshot) 1833 notifyIfNeeded(for: entry, snapshot: snapshot, previousSnapshot: previousSnapshot)
1814 return entry 1834 return entry
1815 } 1835 }
1816 1836
1837 /// A single snapshot written on its own. `persistHistory` rewrites every
1838 /// row because it cannot tell what changed; these callers can, and at the
1839 /// Pro+ cap that is the difference between 23 ms and 656 ms.
1840 private func storeHistoryEntry(_ entry: HistoryEntry, replacingExisting: Bool) {
1841 if historyPersistenceSuspended {
1842 historyPersistenceDirty = true
1843 return
1844 }
1845 if replacingExisting {
1846 DomainDataPortabilityService.updateHistoryEntry(
1847 entry,
1848 defaults: defaults,
1849 historyLocation: historyLocation
1850 )
1851 } else {
1852 DomainDataPortabilityService.appendHistoryEntry(
1853 entry,
1854 cap: effectiveHistoryLimit,
1855 defaults: defaults,
1856 historyLocation: historyLocation
1857 )
1858 }
1859 refreshDataLifecycleSummary()
1860 }
1861
1862 private func removeStoredHistory(ids: Set<UUID>) {
1863 if historyPersistenceSuspended {
1864 historyPersistenceDirty = true
1865 return
1866 }
1867 DomainDataPortabilityService.removeHistoryEntries(
1868 ids: ids,
1869 defaults: defaults,
1870 historyLocation: historyLocation
1871 )
1872 refreshDataLifecycleSummary()
1873 }
1874
1875 /// Rewrites the whole store. Only the auto-prune setting needs this — it
1876 /// drops rows from the middle and cannot say which. Every other writer
1877 /// goes through `storeHistoryEntry` or `removeStoredHistory`.
1817 private func persistHistory() { 1878 private func persistHistory() {
1818 if historyPersistenceSuspended { 1879 if historyPersistenceSuspended {
1819 historyPersistenceDirty = true 1880 historyPersistenceDirty = true
1820 return 1881 return
1821 } 1882 }
1822 let persistStartedAt = DomainDebugLog.signpostStart("DomainViewModel.persistHistory") 1883 let persistStartedAt = DomainDebugLog.signpostStart("DomainViewModel.persistHistory")
1823 DomainDataPortabilityService.saveHistoryEntries(history, defaults: defaults) 1884 DomainDataPortabilityService.saveHistoryEntries(history, defaults: defaults, historyLocation: historyLocation)
1824 refreshDataLifecycleSummary() 1885 refreshDataLifecycleSummary()
1825 DomainDebugLog.signpostEnd("DomainViewModel.persistHistory", start: persistStartedAt, extra: "count=\(history.count)") 1886 DomainDebugLog.signpostEnd("DomainViewModel.persistHistory", start: persistStartedAt, extra: "count=\(history.count)")
1826 } 1887 }
@@ -1840,7 +1901,7 @@ final class DomainViewModel {
1840 func updateHistoryNote(_ note: String, for entry: HistoryEntry) { 1901 func updateHistoryNote(_ note: String, for entry: HistoryEntry) {
1841 guard let index = history.firstIndex(where: { $0.id == entry.id }) else { return } 1902 guard let index = history.firstIndex(where: { $0.id == entry.id }) else { return }
1842 history[index].note = note.trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty 1903 history[index].note = note.trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty
1843 persistHistory() 1904 storeHistoryEntry(history[index], replacingExisting: true)
1844 } 1905 }
1845 1906
1846 #if DEBUG 1907 #if DEBUG
@@ -1891,15 +1952,20 @@ final class DomainViewModel {
1891 1952
1892 if historyPersistenceDirty { 1953 if historyPersistenceDirty {
1893 historyPersistenceDirty = false 1954 historyPersistenceDirty = false
1894 DomainDataPortabilityService.saveHistoryEntries(history, defaults: defaults) 1955 DomainDataPortabilityService.saveHistoryEntries(history, defaults: defaults, historyLocation: historyLocation)
1895 } 1956 }
1896 1957
1897 refreshDataLifecycleSummary() 1958 refreshDataLifecycleSummary()
1898 } 1959 }
1899 1960
1961 /// The number of snapshots this install keeps: the user's auto-prune
1962 /// choice, never above the store's own ceiling.
1963 private var effectiveHistoryLimit: Int {
1964 min(historyAutoPruneOption.keepCount ?? Self.maxHistory, Self.maxHistory)
1965 }
1966
1900 private func trimHistoryToLimit() { 1967 private func trimHistoryToLimit() {
1901 let hardLimit = historyAutoPruneOption.keepCount ?? Self.maxHistory 1968 history = Array(history.prefix(effectiveHistoryLimit))
1902 history = Array(history.prefix(min(hardLimit, Self.maxHistory)))
1903 } 1969 }
1904 1970
1905 private func nextSnapshotIndex(for domain: String, trackedDomainID: UUID?) -> Int { 1971 private func nextSnapshotIndex(for domain: String, trackedDomainID: UUID?) -> Int {
@@ -2024,18 +2090,16 @@ final class DomainViewModel {
2024 2090
2025 private func linkTrackedDomainHistory(for domain: String) { 2091 private func linkTrackedDomainHistory(for domain: String) {
2026 guard let trackedDomain = trackedDomain(for: domain) else { return } 2092 guard let trackedDomain = trackedDomain(for: domain) else { return }
2027 var didChange = false
2028 2093
2094 var relinked: [HistoryEntry] = []
2029 for index in history.indices where history[index].domain.caseInsensitiveCompare(domain) == .orderedSame { 2095 for index in history.indices where history[index].domain.caseInsensitiveCompare(domain) == .orderedSame {
2030 if history[index].trackedDomainID != trackedDomain.id { 2096 if history[index].trackedDomainID != trackedDomain.id {
2031 history[index].trackedDomainID = trackedDomain.id 2097 history[index].trackedDomainID = trackedDomain.id
2032 didChange = true 2098 relinked.append(history[index])
2033 } 2099 }
2034 } 2100 }
2035 2101
2036 if didChange { 2102 relinked.forEach { storeHistoryEntry($0, replacingExisting: true) }
2037 persistHistory()
2038 }
2039 2103
2040 if let latestEntry = history.first(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }), 2104 if let latestEntry = history.first(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }),
2041 let trackedIndex = trackedDomains.firstIndex(where: { $0.id == trackedDomain.id }) { 2105 let trackedIndex = trackedDomains.firstIndex(where: { $0.id == trackedDomain.id }) {
@@ -3013,9 +3077,15 @@ final class DomainViewModel {
3013 ) 3077 )
3014 } 3078 }
3015 3079
3016 private static func loadHistoryEntries(defaults: UserDefaults) -> [HistoryEntry] { 3080 private static func loadHistoryEntries(
3017 DataMigrationService.migrateIfNeeded(defaults: defaults) 3081 defaults: UserDefaults,
3018 return DomainDataPortabilityService.loadHistoryEntries(defaults: defaults) 3082 historyLocation: HistoryFileStore.Location
3083 ) -> [HistoryEntry] {
3084 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
3085 return DomainDataPortabilityService.loadHistoryEntries(
3086 defaults: defaults,
3087 historyLocation: historyLocation
3088 )
3019 } 3089 }
3020 3090
3021 private static func loadHistoryAutoPruneOption(defaults: UserDefaults) -> HistoryAutoPruneOption { 3091 private static func loadHistoryAutoPruneOption(defaults: UserDefaults) -> HistoryAutoPruneOption {
@@ -3026,8 +3096,11 @@ final class DomainViewModel {
3026 return option 3096 return option
3027 } 3097 }
3028 3098
3029 private static func loadTrackedDomains(defaults: UserDefaults) -> [TrackedDomain] { 3099 private static func loadTrackedDomains(
3030 DataMigrationService.migrateIfNeeded(defaults: defaults) 3100 defaults: UserDefaults,
3101 historyLocation: HistoryFileStore.Location
3102 ) -> [TrackedDomain] {
3103 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
3031 return DomainDataPortabilityService.loadTrackedDomains(defaults: defaults) 3104 return DomainDataPortabilityService.loadTrackedDomains(defaults: defaults)
3032 } 3105 }
3033 3106
@@ -3037,8 +3110,11 @@ final class DomainViewModel {
3037 refreshDataLifecycleSummary() 3110 refreshDataLifecycleSummary()
3038 } 3111 }
3039 3112
3040 static func loadWorkflows(defaults: UserDefaults) -> [DomainWorkflow] { 3113 static func loadWorkflows(
3041 DataMigrationService.migrateIfNeeded(defaults: defaults) 3114 defaults: UserDefaults,
3115 historyLocation: HistoryFileStore.Location
3116 ) -> [DomainWorkflow] {
3117 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
3042 return DomainDataPortabilityService.loadWorkflows(defaults: defaults) 3118 return DomainDataPortabilityService.loadWorkflows(defaults: defaults)
3043 } 3119 }
3044 3120
DomainDig/HistoryFileStore.swift added +207
@@ -0,0 +1,207 @@
1import Foundation
2
3/// One row of the history index: the fields the list, the filters and the
4/// sorts read, without the snapshot behind them.
5///
6/// `filteredHistory` searches on `domain`, filters on `timestamp` and
7/// `changeSummary`, and sorts on those plus `changeCount` — so a reader that
8/// only lists history never needs the DNS sections, headers, subdomain lists
9/// or timelines that make up almost all of an entry's bytes.
10struct HistoryIndexRow: Codable, Identifiable, Equatable, Sendable {
11 let id: UUID
12 let domain: String
13 let timestamp: Date
14 var trackedDomainID: UUID?
15 var note: String?
16 var snapshotIndex: Int?
17 var changeCount: Int
18 var severitySummary: ChangeSeverity?
19 var hasChanges: Bool
20 var availabilityStatus: DomainAvailabilityStatus?
21 var resultSource: LookupResultSource
22
23 nonisolated init(entry: HistoryEntry) {
24 id = entry.id
25 domain = entry.domain
26 timestamp = entry.timestamp
27 trackedDomainID = entry.trackedDomainID
28 note = entry.note
29 snapshotIndex = entry.snapshotIndex
30 changeCount = entry.changeCount
31 severitySummary = entry.severitySummary
32 hasChanges = entry.changeSummary?.hasChanges ?? false
33 availabilityStatus = entry.availabilityResult?.status
34 resultSource = entry.resultSource
35 }
36}
37
38/// History on disk: one JSON file per snapshot plus an index, under D3's
39/// "files plus an index, keep a cap, no dependency" decision.
40///
41/// The substrate it replaces kept every snapshot in one `UserDefaults` key and
42/// rewrote the whole blob on every save. Measured at the Pro+ cap of 2000 rows
43/// that was 6,564 KiB, 214 ms to save and 209 ms to load, with the save on the
44/// main actor after every lookup (A1). Per-entry files make a single-snapshot
45/// write independent of how many snapshots exist, and the index makes listing
46/// independent of their contents.
47///
48/// `UserDefaults` is still the home for the small stores — tracked domains,
49/// workflows, settings. Only history is large enough to be worth a directory.
50enum HistoryFileStore {
51
52 /// Injected so tests get a scratch directory instead of the real one, the
53 /// same way `defaults:` threads the store through the view model.
54 nonisolated struct Location: Sendable {
55 let root: URL
56
57 static let `default` = Location(
58 root: FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
59 .appendingPathComponent("History", isDirectory: true)
60 )
61
62 var indexFile: URL { root.appendingPathComponent("index.json", isDirectory: false) }
63 var entriesDirectory: URL { root.appendingPathComponent("entries", isDirectory: true) }
64
65 func entryFile(id: UUID) -> URL {
66 entriesDirectory.appendingPathComponent("\(id.uuidString).json", isDirectory: false)
67 }
68 }
69
70 // MARK: Reading
71
72 /// The index alone. This is what a list view wants.
73 static func loadIndex(at location: Location = .default) -> [HistoryIndexRow] {
74 guard let data = try? Data(contentsOf: location.indexFile),
75 let rows = try? decoder().decode([HistoryIndexRow].self, from: data)
76 else { return [] }
77 return sorted(rows)
78 }
79
80 static func loadEntry(id: UUID, at location: Location = .default) -> HistoryEntry? {
81 guard let data = try? Data(contentsOf: location.entryFile(id: id)) else { return nil }
82 return try? decoder().decode(HistoryEntry.self, from: data)
83 }
84
85 /// Every snapshot in full. Backup, export and the migration need this; the
86 /// UI does not, and asking for it at the Pro+ cap reads 2000 files.
87 static func loadAllEntries(at location: Location = .default) -> [HistoryEntry] {
88 let rows = loadIndex(at: location)
89 guard !rows.isEmpty else { return [] }
90 return rows.compactMap { loadEntry(id: $0.id, at: location) }
91 }
92
93 // MARK: Writing
94
95 /// Appends one snapshot: one file written, one index rewritten. The cost
96 /// does not depend on how many snapshots are already stored, which is the
97 /// whole reason for the directory. A `replaceAll` of the same array costs
98 /// an encode of every row instead.
99 static func append(_ entry: HistoryEntry, cap: Int, at location: Location = .default) {
100 guard ensureDirectories(at: location), write(entry, at: location) else { return }
101
102 var rows = loadIndex(at: location).filter { $0.id != entry.id }
103 rows.append(HistoryIndexRow(entry: entry))
104 rows = sorted(rows)
105
106 let kept = Array(rows.prefix(cap))
107 for dropped in rows.dropFirst(cap) {
108 try? FileManager.default.removeItem(at: location.entryFile(id: dropped.id))
109 }
110 writeIndex(kept, at: location)
111 }
112
113 /// Replaces one snapshot in place, for a note edit or a re-linked tracked
114 /// domain. Same cost as an append.
115 static func update(_ entry: HistoryEntry, at location: Location = .default) {
116 guard ensureDirectories(at: location), write(entry, at: location) else { return }
117
118 let rows = loadIndex(at: location).map { $0.id == entry.id ? HistoryIndexRow(entry: entry) : $0 }
119 writeIndex(sorted(rows), at: location)
120 }
121
122 static func remove(ids: Set<UUID>, at location: Location = .default) {
123 guard !ids.isEmpty else { return }
124 for id in ids {
125 try? FileManager.default.removeItem(at: location.entryFile(id: id))
126 }
127 writeIndex(loadIndex(at: location).filter { !ids.contains($0.id) }, at: location)
128 }
129
130 /// Writes the store from scratch. For the migration off `UserDefaults`, a
131 /// backup import and a prune — the cases that really do change every row.
132 /// Everything else should use `append` or `update`.
133 static func replaceAll(with entries: [HistoryEntry], cap: Int, at location: Location = .default) {
134 guard ensureDirectories(at: location) else { return }
135
136 let rows = Array(sorted(entries.map(HistoryIndexRow.init(entry:))).prefix(cap))
137 let keptIDs = Set(rows.map(\.id))
138 var byID: [UUID: HistoryEntry] = [:]
139 for entry in entries where keptIDs.contains(entry.id) {
140 byID[entry.id] = entry
141 }
142
143 for id in keptIDs {
144 guard let entry = byID[id] else { continue }
145 _ = write(entry, at: location)
146 }
147 for stale in onDiskEntryIDs(at: location).subtracting(keptIDs) {
148 try? FileManager.default.removeItem(at: location.entryFile(id: stale))
149 }
150 writeIndex(rows, at: location)
151 }
152
153 /// `nonisolated` because the data reset's wipe runs off the main actor and
154 /// removing a directory touches no `Codable` conformance. The rest of this
155 /// type cannot follow: `HistoryEntry`'s conformance is MainActor-isolated
156 /// by the project's default isolation.
157 nonisolated static func removeAll(at location: Location = .default) {
158 try? FileManager.default.removeItem(at: location.root)
159 }
160
161 // MARK: Internals
162
163 /// Newest first, matching what the `UserDefaults` store's merge returned
164 /// and what every reader downstream assumes.
165 private static func sorted(_ rows: [HistoryIndexRow]) -> [HistoryIndexRow] {
166 var seen: Set<UUID> = []
167 return rows
168 .filter { seen.insert($0.id).inserted }
169 .sorted { lhs, rhs in
170 if lhs.timestamp != rhs.timestamp {
171 return lhs.timestamp > rhs.timestamp
172 }
173 return lhs.domain.localizedCaseInsensitiveCompare(rhs.domain) == .orderedAscending
174 }
175 }
176
177 /// Writes unconditionally. The previous version read the existing file
178 /// back to compare first, which made appending one snapshot to a full
179 /// store cost 2000 reads — measured at 890 ms against the blob's 216 ms.
180 private static func write(_ entry: HistoryEntry, at location: Location) -> Bool {
181 guard let data = try? encoder().encode(entry) else { return false }
182 return (try? data.write(to: location.entryFile(id: entry.id), options: .atomic)) != nil
183 }
184
185 private static func writeIndex(_ rows: [HistoryIndexRow], at location: Location) {
186 guard let data = try? encoder().encode(rows) else { return }
187 try? data.write(to: location.indexFile, options: .atomic)
188 }
189
190 private static func onDiskEntryIDs(at location: Location) -> Set<UUID> {
191 let files = (try? FileManager.default.contentsOfDirectory(
192 at: location.entriesDirectory,
193 includingPropertiesForKeys: nil
194 )) ?? []
195 return Set(files.compactMap { UUID(uuidString: $0.deletingPathExtension().lastPathComponent) })
196 }
197
198 private static func ensureDirectories(at location: Location) -> Bool {
199 (try? FileManager.default.createDirectory(
200 at: location.entriesDirectory,
201 withIntermediateDirectories: true
202 )) != nil
203 }
204
205 private static func encoder() -> JSONEncoder { JSONEncoder() }
206 private static func decoder() -> JSONDecoder { JSONDecoder() }
207}
DomainDig/ScheduledReportService.swift +1 −1
@@ -116,7 +116,7 @@ final class ScheduledReportService {
116 return ScheduledReportOutcome(success: false, message: "No tracked domains to report on.", log: nil) 116 return ScheduledReportOutcome(success: false, message: "No tracked domains to report on.", log: nil)
117 } 117 }
118 118
119 let history = DomainDataPortabilityService.loadHistoryEntries() 119 let history = DomainDataPortabilityService.loadHistoryEntries(historyLocation: .default)
120 let builder = DomainReportBuilder() 120 let builder = DomainReportBuilder()
121 let reports = trackedDomains.compactMap { trackedDomain -> DomainReport? in 121 let reports = trackedDomains.compactMap { trackedDomain -> DomainReport? in
122 let entry = history.first { entry in 122 let entry = history.first { entry in
DomainDigTests/DataMigrationServiceTests.swift +21 −8
@@ -14,22 +14,31 @@ final class DataMigrationServiceTests: XCTestCase {
14 private var defaults: UserDefaults! 14 private var defaults: UserDefaults!
15 private let base = Date(timeIntervalSince1970: 1_700_000_000) 15 private let base = Date(timeIntervalSince1970: 1_700_000_000)
16 16
17 /// v2 moves history into a directory, so an ephemeral `UserDefaults` suite
18 /// is no longer enough to keep these off the real store.
19 private var historyLocation = HistoryFileStore.Location.default
20
17 override func setUp() { 21 override func setUp() {
18 super.setUp() 22 super.setUp()
19 defaults = UserDefaults(suiteName: suiteName) 23 defaults = UserDefaults(suiteName: suiteName)
20 defaults.removePersistentDomain(forName: suiteName) 24 defaults.removePersistentDomain(forName: suiteName)
25 historyLocation = HistoryFileStore.Location(
26 root: URL(fileURLWithPath: NSTemporaryDirectory())
27 .appendingPathComponent("DomainDigMigrationTest-\(UUID().uuidString)", isDirectory: true)
28 )
21 } 29 }
22 30
23 override func tearDown() { 31 override func tearDown() {
24 defaults.removePersistentDomain(forName: suiteName) 32 defaults.removePersistentDomain(forName: suiteName)
25 defaults = nil 33 defaults = nil
34 HistoryFileStore.removeAll(at: historyLocation)
26 super.tearDown() 35 super.tearDown()
27 } 36 }
28 37
29 func testFreshStoreIsStampedAtCurrentVersion() { 38 func testFreshStoreIsStampedAtCurrentVersion() {
30 XCTAssertEqual(DataMigrationService.storeSchemaVersion(defaults: defaults), 0) 39 XCTAssertEqual(DataMigrationService.storeSchemaVersion(defaults: defaults), 0)
31 40
32 DataMigrationService.migrateIfNeeded(defaults: defaults) 41 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
33 42
34 XCTAssertEqual( 43 XCTAssertEqual(
35 DataMigrationService.storeSchemaVersion(defaults: defaults), 44 DataMigrationService.storeSchemaVersion(defaults: defaults),
@@ -41,13 +50,17 @@ final class DataMigrationServiceTests: XCTestCase {
41 let legacy = [WatchedDomain(domain: "legacy.example", createdAt: base, lastKnownAvailability: .registered)] 50 let legacy = [WatchedDomain(domain: "legacy.example", createdAt: base, lastKnownAvailability: .registered)]
42 defaults.set(try JSONEncoder().encode(legacy), forKey: "watchedDomains") 51 defaults.set(try JSONEncoder().encode(legacy), forKey: "watchedDomains")
43 52
44 DataMigrationService.migrateIfNeeded(defaults: defaults) 53 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
45 54
46 let tracked = DomainDataPortabilityService.loadTrackedDomains(defaults: defaults) 55 let tracked = DomainDataPortabilityService.loadTrackedDomains(defaults: defaults)
47 XCTAssertEqual(tracked.map(\.domain), ["legacy.example"]) 56 XCTAssertEqual(tracked.map(\.domain), ["legacy.example"])
48 XCTAssertNil(defaults.data(forKey: "watchedDomains"), "legacy key is dropped after migration") 57 XCTAssertNil(defaults.data(forKey: "watchedDomains"), "legacy key is dropped after migration")
49 XCTAssertNotNil(defaults.data(forKey: "trackedDomains"), "data is rewritten under the current key") 58 XCTAssertNotNil(defaults.data(forKey: "trackedDomains"), "data is rewritten under the current key")
50 XCTAssertEqual(DataMigrationService.storeSchemaVersion(defaults: defaults), 1) 59 XCTAssertEqual(
60 DataMigrationService.storeSchemaVersion(defaults: defaults),
61 DataMigrationService.currentStoreSchemaVersion,
62 "the runner stops short of this build's version"
63 )
51 } 64 }
52 65
53 func testMigrationDeduplicatesTheStoredBlobInPlace() throws { 66 func testMigrationDeduplicatesTheStoredBlobInPlace() throws {
@@ -57,7 +70,7 @@ final class DataMigrationServiceTests: XCTestCase {
57 ] 70 ]
58 defaults.set(try JSONEncoder().encode(dupes), forKey: "trackedDomains") 71 defaults.set(try JSONEncoder().encode(dupes), forKey: "trackedDomains")
59 72
60 DataMigrationService.migrateIfNeeded(defaults: defaults) 73 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
61 74
62 let data = try XCTUnwrap(defaults.data(forKey: "trackedDomains")) 75 let data = try XCTUnwrap(defaults.data(forKey: "trackedDomains"))
63 let stored = try JSONDecoder().decode([TrackedDomain].self, from: data) 76 let stored = try JSONDecoder().decode([TrackedDomain].self, from: data)
@@ -70,10 +83,10 @@ final class DataMigrationServiceTests: XCTestCase {
70 forKey: "trackedDomains" 83 forKey: "trackedDomains"
71 ) 84 )
72 85
73 DataMigrationService.migrateIfNeeded(defaults: defaults) 86 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
74 let afterFirst = defaults.data(forKey: "trackedDomains") 87 let afterFirst = defaults.data(forKey: "trackedDomains")
75 88
76 DataMigrationService.migrateIfNeeded(defaults: defaults) 89 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
77 let afterSecond = defaults.data(forKey: "trackedDomains") 90 let afterSecond = defaults.data(forKey: "trackedDomains")
78 91
79 XCTAssertEqual(afterFirst, afterSecond, "a second run makes no further changes") 92 XCTAssertEqual(afterFirst, afterSecond, "a second run makes no further changes")
@@ -91,7 +104,7 @@ final class DataMigrationServiceTests: XCTestCase {
91 // Already at v1, so the v1 step must not re-run: a leftover legacy blob 104 // Already at v1, so the v1 step must not re-run: a leftover legacy blob
92 // is left exactly as found. 105 // is left exactly as found.
93 defaults.set(Data("x".utf8), forKey: "watchedDomains") 106 defaults.set(Data("x".utf8), forKey: "watchedDomains")
94 DataMigrationService.migrateIfNeeded(defaults: defaults) 107 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
95 XCTAssertNotNil(defaults.data(forKey: "watchedDomains"), "v1 is treated as already applied; no re-run") 108 XCTAssertNotNil(defaults.data(forKey: "watchedDomains"), "v1 is treated as already applied; no re-run")
96 } 109 }
97 110
@@ -101,7 +114,7 @@ final class DataMigrationServiceTests: XCTestCase {
101 let blob = try JSONEncoder().encode([TrackedDomain(domain: "keep.example", updatedAt: base)]) 114 let blob = try JSONEncoder().encode([TrackedDomain(domain: "keep.example", updatedAt: base)])
102 defaults.set(blob, forKey: "trackedDomains") 115 defaults.set(blob, forKey: "trackedDomains")
103 116
104 DataMigrationService.migrateIfNeeded(defaults: defaults) 117 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
105 118
106 XCTAssertEqual(DataMigrationService.storeSchemaVersion(defaults: defaults), future, "must never downgrade") 119 XCTAssertEqual(DataMigrationService.storeSchemaVersion(defaults: defaults), future, "must never downgrade")
107 XCTAssertEqual(defaults.data(forKey: "trackedDomains"), blob, "future-version data is left byte-for-byte") 120 XCTAssertEqual(defaults.data(forKey: "trackedDomains"), blob, "future-version data is left byte-for-byte")
DomainDigTests/DomainViewModelStoreTests.swift +13 −5
@@ -13,14 +13,22 @@ final class DomainViewModelStoreTests: XCTestCase {
13 private var suiteName = "" 13 private var suiteName = ""
14 private var scratch = UserDefaults.standard 14 private var scratch = UserDefaults.standard
15 15
16 /// History lives in a directory now, so the scratch store has two halves.
17 private var historyLocation = HistoryFileStore.Location.default
18
16 override func setUpWithError() throws { 19 override func setUpWithError() throws {
17 try super.setUpWithError() 20 try super.setUpWithError()
18 suiteName = "net.cleberg.DomainDig.tests.\(UUID().uuidString)" 21 suiteName = "net.cleberg.DomainDig.tests.\(UUID().uuidString)"
19 scratch = try XCTUnwrap(UserDefaults(suiteName: suiteName)) 22 scratch = try XCTUnwrap(UserDefaults(suiteName: suiteName))
23 historyLocation = HistoryFileStore.Location(
24 root: URL(fileURLWithPath: NSTemporaryDirectory())
25 .appendingPathComponent("DomainDigVMTest-\(UUID().uuidString)", isDirectory: true)
26 )
20 } 27 }
21 28
22 override func tearDown() { 29 override func tearDown() {
23 UserDefaults.standard.removePersistentDomain(forName: suiteName) 30 UserDefaults.standard.removePersistentDomain(forName: suiteName)
31 HistoryFileStore.removeAll(at: historyLocation)
24 super.tearDown() 32 super.tearDown()
25 } 33 }
26 34
@@ -32,7 +40,7 @@ final class DomainViewModelStoreTests: XCTestCase {
32 private static var retained: [DomainViewModel] = [] 40 private static var retained: [DomainViewModel] = []
33 41
34 private func makeViewModel() -> DomainViewModel { 42 private func makeViewModel() -> DomainViewModel {
35 let viewModel = DomainViewModel(defaults: scratch) 43 let viewModel = DomainViewModel(defaults: scratch, historyLocation: historyLocation)
36 Self.retained.append(viewModel) 44 Self.retained.append(viewModel)
37 return viewModel 45 return viewModel
38 } 46 }
@@ -68,7 +76,7 @@ final class DomainViewModelStoreTests: XCTestCase {
68 [TrackedDomain(domain: "tracked.example", createdAt: Date(), updatedAt: Date())], 76 [TrackedDomain(domain: "tracked.example", createdAt: Date(), updatedAt: Date())],
69 defaults: scratch 77 defaults: scratch
70 ) 78 )
71 DomainDataPortabilityService.saveHistoryEntries(makeEntries(3), defaults: scratch) 79 DomainDataPortabilityService.saveHistoryEntries(makeEntries(3), defaults: scratch, historyLocation: historyLocation)
72 80
73 let viewModel = makeViewModel() 81 let viewModel = makeViewModel()
74 82
@@ -98,7 +106,7 @@ final class DomainViewModelStoreTests: XCTestCase {
98 let other = try XCTUnwrap(UserDefaults(suiteName: otherName)) 106 let other = try XCTUnwrap(UserDefaults(suiteName: otherName))
99 107
100 let first = makeViewModel() 108 let first = makeViewModel()
101 let second = DomainViewModel(defaults: other) 109 let second = DomainViewModel(defaults: other, historyLocation: historyLocation)
102 Self.retained.append(second) 110 Self.retained.append(second)
103 111
104 first.addRecentSearch("first.example") 112 first.addRecentSearch("first.example")
@@ -142,7 +150,7 @@ final class DomainViewModelStoreTests: XCTestCase {
142 viewModel.setHistoryAutoPruneOption(.keep50) 150 viewModel.setHistoryAutoPruneOption(.keep50)
143 151
144 XCTAssertEqual(viewModel.history.count, 50) 152 XCTAssertEqual(viewModel.history.count, 50)
145 XCTAssertEqual(DomainDataPortabilityService.loadHistoryEntries(defaults: scratch).count, 50) 153 XCTAssertEqual(DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation).count, 50)
146 } 154 }
147 155
148 /// Pruning trims from the front, so the rows kept must be the newest ones. 156 /// Pruning trims from the front, so the rows kept must be the newest ones.
@@ -172,7 +180,7 @@ final class DomainViewModelStoreTests: XCTestCase {
172 /// A store already over the cap must still be readable. Pruning happens on 180 /// A store already over the cap must still be readable. Pruning happens on
173 /// a write, not on a read, so loading must not drop rows. 181 /// a write, not on a read, so loading must not drop rows.
174 func testAStoreAlreadyOverTheCapLoadsEveryRow() { 182 func testAStoreAlreadyOverTheCapLoadsEveryRow() {
175 DomainDataPortabilityService.saveHistoryEntries(makeEntries(300), defaults: scratch) 183 DomainDataPortabilityService.saveHistoryEntries(makeEntries(300), defaults: scratch, historyLocation: historyLocation)
176 184
177 XCTAssertEqual(makeViewModel().history.count, 300) 185 XCTAssertEqual(makeViewModel().history.count, 300)
178 } 186 }
DomainDigTests/HistoryEntryCodableTests.swift +15 −2
@@ -126,8 +126,21 @@ final class HistoryEntryCodableTests: XCTestCase {
126 let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) 126 let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
127 defer { defaults.removePersistentDomain(forName: suite) } 127 defer { defaults.removePersistentDomain(forName: suite) }
128 128
129 DomainDataPortabilityService.saveHistoryEntries([makeEntry()], defaults: defaults) 129 let historyLocation = HistoryFileStore.Location(
130 let loaded = DomainDataPortabilityService.loadHistoryEntries(defaults: defaults) 130 root: URL(fileURLWithPath: NSTemporaryDirectory())
131 .appendingPathComponent("DomainDigCodableTest-\(UUID().uuidString)", isDirectory: true)
132 )
133 defer { HistoryFileStore.removeAll(at: historyLocation) }
134
135 DomainDataPortabilityService.saveHistoryEntries(
136 [makeEntry()],
137 defaults: defaults,
138 historyLocation: historyLocation
139 )
140 let loaded = DomainDataPortabilityService.loadHistoryEntries(
141 defaults: defaults,
142 historyLocation: historyLocation
143 )
131 144
132 XCTAssertEqual(loaded.count, 1, "entry was silently dropped by the load path") 145 XCTAssertEqual(loaded.count, 1, "entry was silently dropped by the load path")
133 XCTAssertEqual(loaded.first?.domain, "example.com") 146 XCTAssertEqual(loaded.first?.domain, "example.com")
DomainDigTests/HistoryStoreTests.swift +195 −22
@@ -18,17 +18,31 @@ final class HistoryStoreTests: XCTestCase {
18 private var suiteName = "" 18 private var suiteName = ""
19 private var scratch = UserDefaults.standard 19 private var scratch = UserDefaults.standard
20 20
21 /// History lives in files now, so a scratch `UserDefaults` is no longer
22 /// enough to keep a test out of the real store — it needs its own
23 /// directory too.
24 private var historyLocation = HistoryFileStore.Location.default
25
21 override func setUpWithError() throws { 26 override func setUpWithError() throws {
22 try super.setUpWithError() 27 try super.setUpWithError()
23 suiteName = "net.cleberg.DomainDig.tests.\(UUID().uuidString)" 28 suiteName = "net.cleberg.DomainDig.tests.\(UUID().uuidString)"
24 scratch = try XCTUnwrap(UserDefaults(suiteName: suiteName)) 29 scratch = try XCTUnwrap(UserDefaults(suiteName: suiteName))
30 historyLocation = Self.scratchLocation()
25 } 31 }
26 32
27 override func tearDown() { 33 override func tearDown() {
28 UserDefaults.standard.removePersistentDomain(forName: suiteName) 34 UserDefaults.standard.removePersistentDomain(forName: suiteName)
35 HistoryFileStore.removeAll(at: historyLocation)
29 super.tearDown() 36 super.tearDown()
30 } 37 }
31 38
39 private static func scratchLocation() -> HistoryFileStore.Location {
40 HistoryFileStore.Location(
41 root: URL(fileURLWithPath: NSTemporaryDirectory())
42 .appendingPathComponent("DomainDigTestHistory-\(UUID().uuidString)", isDirectory: true)
43 )
44 }
45
32 private func entries(_ count: Int) -> [HistoryEntry] { 46 private func entries(_ count: Int) -> [HistoryEntry] {
33 (0..<count).map { SnapshotFixture.historyEntry(index: $0) } 47 (0..<count).map { SnapshotFixture.historyEntry(index: $0) }
34 } 48 }
@@ -38,8 +52,8 @@ final class HistoryStoreTests: XCTestCase {
38 func testTwoThousandEntriesSurviveASaveAndLoad() { 52 func testTwoThousandEntriesSurviveASaveAndLoad() {
39 let saved = entries(Self.proPlusCap) 53 let saved = entries(Self.proPlusCap)
40 54
41 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch) 55 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch, historyLocation: historyLocation)
42 let loaded = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch) 56 let loaded = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
43 57
44 XCTAssertEqual(loaded.count, Self.proPlusCap, "the store dropped or added rows") 58 XCTAssertEqual(loaded.count, Self.proPlusCap, "the store dropped or added rows")
45 XCTAssertEqual(Set(loaded.map(\.id)), Set(saved.map(\.id)), "the store changed which rows exist") 59 XCTAssertEqual(Set(loaded.map(\.id)), Set(saved.map(\.id)), "the store changed which rows exist")
@@ -49,9 +63,9 @@ final class HistoryStoreTests: XCTestCase {
49 /// history list, the dashboard's recent activity, the diff view's 63 /// history list, the dashboard's recent activity, the diff view's
50 /// "previous snapshot" — takes that for granted. 64 /// "previous snapshot" — takes that for granted.
51 func testTheStoreReturnsRowsNewestFirst() { 65 func testTheStoreReturnsRowsNewestFirst() {
52 DomainDataPortabilityService.saveHistoryEntries(entries(Self.proPlusCap), defaults: scratch) 66 DomainDataPortabilityService.saveHistoryEntries(entries(Self.proPlusCap), defaults: scratch, historyLocation: historyLocation)
53 67
54 let loaded = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch) 68 let loaded = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
55 69
56 XCTAssertEqual(loaded.map(\.timestamp), loaded.map(\.timestamp).sorted(by: >)) 70 XCTAssertEqual(loaded.map(\.timestamp), loaded.map(\.timestamp).sorted(by: >))
57 XCTAssertEqual(loaded.first?.snapshotIndex, Self.proPlusCap - 1) 71 XCTAssertEqual(loaded.first?.snapshotIndex, Self.proPlusCap - 1)
@@ -61,10 +75,10 @@ final class HistoryStoreTests: XCTestCase {
61 func testNoRowIsDuplicatedAcrossRepeatedSaves() { 75 func testNoRowIsDuplicatedAcrossRepeatedSaves() {
62 let saved = entries(Self.proPlusCap) 76 let saved = entries(Self.proPlusCap)
63 77
64 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch) 78 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch, historyLocation: historyLocation)
65 let once = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch) 79 let once = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
66 DomainDataPortabilityService.saveHistoryEntries(once, defaults: scratch) 80 DomainDataPortabilityService.saveHistoryEntries(once, defaults: scratch, historyLocation: historyLocation)
67 let twice = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch) 81 let twice = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
68 82
69 XCTAssertEqual(twice.count, Self.proPlusCap) 83 XCTAssertEqual(twice.count, Self.proPlusCap)
70 XCTAssertEqual(Set(twice.map(\.id)).count, Self.proPlusCap, "a row was duplicated") 84 XCTAssertEqual(Set(twice.map(\.id)).count, Self.proPlusCap, "a row was duplicated")
@@ -77,9 +91,9 @@ final class HistoryStoreTests: XCTestCase {
77 func testEveryPopulatedFieldSurvivesTheRoundTrip() throws { 91 func testEveryPopulatedFieldSurvivesTheRoundTrip() throws {
78 let original = SnapshotFixture.historyEntry(index: 7) 92 let original = SnapshotFixture.historyEntry(index: 7)
79 93
80 DomainDataPortabilityService.saveHistoryEntries([original], defaults: scratch) 94 DomainDataPortabilityService.saveHistoryEntries([original], defaults: scratch, historyLocation: historyLocation)
81 let restored = try XCTUnwrap( 95 let restored = try XCTUnwrap(
82 DomainDataPortabilityService.loadHistoryEntries(defaults: scratch).first 96 DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation).first
83 ) 97 )
84 98
85 XCTAssertEqual(restored.id, original.id) 99 XCTAssertEqual(restored.id, original.id)
@@ -135,23 +149,34 @@ final class HistoryStoreTests: XCTestCase {
135 149
136 func testABackupAtTheCapRestoresEveryRow() throws { 150 func testABackupAtTheCapRestoresEveryRow() throws {
137 let saved = entries(Self.proPlusCap) 151 let saved = entries(Self.proPlusCap)
138 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch) 152 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch, historyLocation: historyLocation)
139 153
140 let backup = try DomainDataPortabilityService.backupData(defaults: scratch) 154 let backup = try DomainDataPortabilityService.backupData(defaults: scratch, historyLocation: historyLocation)
141 155
142 let restoreName = "net.cleberg.DomainDig.tests.\(UUID().uuidString)" 156 let restoreName = "net.cleberg.DomainDig.tests.\(UUID().uuidString)"
143 defer { UserDefaults.standard.removePersistentDomain(forName: restoreName) } 157 defer { UserDefaults.standard.removePersistentDomain(forName: restoreName) }
144 let restoreStore = try XCTUnwrap(UserDefaults(suiteName: restoreName)) 158 let restoreStore = try XCTUnwrap(UserDefaults(suiteName: restoreName))
159 let restoreLocation = Self.scratchLocation()
160 defer { HistoryFileStore.removeAll(at: restoreLocation) }
145 161
146 let preview = try DomainDataPortabilityService.prepareImport( 162 let preview = try DomainDataPortabilityService.prepareImport(
147 data: backup, 163 data: backup,
148 fileName: "backup.json", 164 fileName: "backup.json",
149 mode: .replace, 165 mode: .replace,
150 defaults: restoreStore 166 defaults: restoreStore,
167 historyLocation: restoreLocation
168 )
169 _ = try DomainDataPortabilityService.applyImport(
170 preview,
171 mode: .replace,
172 defaults: restoreStore,
173 historyLocation: restoreLocation
151 ) 174 )
152 _ = try DomainDataPortabilityService.applyImport(preview, mode: .replace, defaults: restoreStore)
153 175
154 let restored = DomainDataPortabilityService.loadHistoryEntries(defaults: restoreStore) 176 let restored = DomainDataPortabilityService.loadHistoryEntries(
177 defaults: restoreStore,
178 historyLocation: restoreLocation
179 )
155 XCTAssertEqual(restored.count, Self.proPlusCap, "the backup round trip changed the row count") 180 XCTAssertEqual(restored.count, Self.proPlusCap, "the backup round trip changed the row count")
156 XCTAssertEqual(Set(restored.map(\.id)), Set(saved.map(\.id)), "the backup round trip changed which rows exist") 181 XCTAssertEqual(Set(restored.map(\.id)), Set(saved.map(\.id)), "the backup round trip changed which rows exist")
157 } 182 }
@@ -159,29 +184,177 @@ final class HistoryStoreTests: XCTestCase {
159 /// A merge import of a backup of the same store must not double every row. 184 /// A merge import of a backup of the same store must not double every row.
160 func testMergingABackupOfTheSameStoreDoesNotDuplicateRows() throws { 185 func testMergingABackupOfTheSameStoreDoesNotDuplicateRows() throws {
161 let saved = entries(500) 186 let saved = entries(500)
162 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch) 187 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch, historyLocation: historyLocation)
163 188
164 let backup = try DomainDataPortabilityService.backupData(defaults: scratch) 189 let backup = try DomainDataPortabilityService.backupData(defaults: scratch, historyLocation: historyLocation)
165 let preview = try DomainDataPortabilityService.prepareImport( 190 let preview = try DomainDataPortabilityService.prepareImport(
166 data: backup, 191 data: backup,
167 fileName: "backup.json", 192 fileName: "backup.json",
168 mode: .merge, 193 mode: .merge,
169 defaults: scratch 194 defaults: scratch,
195 historyLocation: historyLocation
170 ) 196 )
171 _ = try DomainDataPortabilityService.applyImport(preview, mode: .merge, defaults: scratch) 197 _ = try DomainDataPortabilityService.applyImport(preview, mode: .merge, defaults: scratch, historyLocation: historyLocation)
172 198
173 let merged = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch) 199 let merged = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
174 XCTAssertEqual(merged.count, 500, "merging a backup of the same store duplicated rows") 200 XCTAssertEqual(merged.count, 500, "merging a backup of the same store duplicated rows")
175 XCTAssertEqual(Set(merged.map(\.id)).count, 500) 201 XCTAssertEqual(Set(merged.map(\.id)).count, 500)
176 } 202 }
177 203
204 // MARK: The v2 migration off UserDefaults
205
206 /// An install that predates the file store has its history in one
207 /// `UserDefaults` blob. The migration must move every row and then clear
208 /// the key, not before.
209 func testTheMigrationMovesHistoryOutOfUserDefaults() throws {
210 let saved = entries(250)
211 let blob = try JSONEncoder().encode(saved)
212 scratch.set(blob, forKey: DomainDataPortabilityService.legacyHistoryBlobKey)
213 scratch.set(1, forKey: DataMigrationService.storeSchemaVersionKey)
214
215 DataMigrationService.migrateIfNeeded(defaults: scratch, historyLocation: historyLocation)
216
217 XCTAssertNil(
218 scratch.data(forKey: DomainDataPortabilityService.legacyHistoryBlobKey),
219 "the legacy blob survived the migration"
220 )
221 let moved = DomainDataPortabilityService.loadHistoryEntries(
222 defaults: scratch,
223 historyLocation: historyLocation
224 )
225 XCTAssertEqual(Set(moved.map(\.id)), Set(saved.map(\.id)))
226 }
227
228 func testTheMigrationIsSafeOnAnEmptyStore() {
229 scratch.set(1, forKey: DataMigrationService.storeSchemaVersionKey)
230
231 DataMigrationService.migrateIfNeeded(defaults: scratch, historyLocation: historyLocation)
232
233 XCTAssertEqual(DataMigrationService.storeSchemaVersion(defaults: scratch), DataMigrationService.currentStoreSchemaVersion)
234 }
235
236 /// Running it twice must not resurrect or duplicate anything.
237 func testTheMigrationIsIdempotent() throws {
238 let saved = entries(50)
239 scratch.set(try JSONEncoder().encode(saved), forKey: DomainDataPortabilityService.legacyHistoryBlobKey)
240 scratch.set(1, forKey: DataMigrationService.storeSchemaVersionKey)
241
242 DataMigrationService.migrateIfNeeded(defaults: scratch, historyLocation: historyLocation)
243 DataMigrationService.migrateIfNeeded(defaults: scratch, historyLocation: historyLocation)
244
245 let moved = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
246 XCTAssertEqual(moved.count, 50)
247 }
248
249 // MARK: Per-entry writes
250
251 /// The reason for the directory: appending one snapshot must not rewrite
252 /// the rest. Measured at the Pro+ cap, 23 ms against 656 ms.
253 func testAppendingOneSnapshotLeavesTheOthersAlone() {
254 let existing = entries(100)
255 DomainDataPortabilityService.saveHistoryEntries(existing, defaults: scratch, historyLocation: historyLocation)
256
257 let fresh = SnapshotFixture.historyEntry(index: 5000)
258 DomainDataPortabilityService.appendHistoryEntry(
259 fresh,
260 cap: 250,
261 defaults: scratch,
262 historyLocation: historyLocation
263 )
264
265 let loaded = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
266 XCTAssertEqual(loaded.count, 101)
267 XCTAssertTrue(loaded.contains { $0.id == fresh.id })
268 XCTAssertEqual(Set(existing.map(\.id)).subtracting(loaded.map(\.id)), [])
269 }
270
271 func testUpdatingOneSnapshotChangesOnlyThatRow() throws {
272 var saved = entries(20)
273 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch, historyLocation: historyLocation)
274
275 saved[3].note = "edited"
276 DomainDataPortabilityService.updateHistoryEntry(saved[3], defaults: scratch, historyLocation: historyLocation)
277
278 let loaded = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
279 XCTAssertEqual(loaded.count, 20)
280 let edited = try XCTUnwrap(loaded.first { $0.id == saved[3].id })
281 XCTAssertEqual(edited.note, "edited")
282 XCTAssertEqual(loaded.filter { $0.note == "edited" }.count, 1)
283 }
284
285 func testRemovingSnapshotsDropsOnlyThoseRows() {
286 let saved = entries(30)
287 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch, historyLocation: historyLocation)
288
289 let doomed = Set(saved.prefix(5).map(\.id))
290 DomainDataPortabilityService.removeHistoryEntries(ids: doomed, defaults: scratch, historyLocation: historyLocation)
291
292 let loaded = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
293 XCTAssertEqual(loaded.count, 25)
294 XCTAssertTrue(Set(loaded.map(\.id)).isDisjoint(with: doomed))
295 }
296
297 /// The index is what a list view reads, and it must agree with the files.
298 func testTheIndexMatchesTheStoredEntries() {
299 let saved = entries(120)
300 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch, historyLocation: historyLocation)
301
302 let index = DomainDataPortabilityService.loadHistoryIndex(defaults: scratch, historyLocation: historyLocation)
303 let full = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
304
305 XCTAssertEqual(index.map(\.id), full.map(\.id))
306 XCTAssertEqual(index.map(\.domain), full.map(\.domain))
307 XCTAssertEqual(index.map(\.timestamp), full.map(\.timestamp))
308 }
309
310 /// Append is the only writer that prunes: it adds the row that pushes the
311 /// oldest one past the limit, so it is the only one that can delete it.
312 func testAppendingPastTheCapDropsTheOldestRow() {
313 let saved = entries(250)
314 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch, historyLocation: historyLocation)
315 let oldest = DomainDataPortabilityService.loadHistoryIndex(
316 defaults: scratch,
317 historyLocation: historyLocation
318 ).last
319
320 DomainDataPortabilityService.appendHistoryEntry(
321 SnapshotFixture.historyEntry(index: 7000),
322 cap: 250,
323 defaults: scratch,
324 historyLocation: historyLocation
325 )
326
327 let loaded = DomainDataPortabilityService.loadHistoryIndex(defaults: scratch, historyLocation: historyLocation)
328 XCTAssertEqual(loaded.count, 250)
329 XCTAssertFalse(loaded.contains { $0.id == oldest?.id }, "the oldest row survived the cap")
330 }
331
332 /// A full rewrite stores what it is given. The old `UserDefaults` store
333 /// had no cap here either, and a backup import that quietly truncated a
334 /// user's history to 250 rows would be data loss.
335 func testAFullRewriteDoesNotImposeACap() {
336 DomainDataPortabilityService.saveHistoryEntries(
337 entries(Self.proPlusCap),
338 defaults: scratch,
339 historyLocation: historyLocation
340 )
341
342 XCTAssertEqual(
343 DomainDataPortabilityService.loadHistoryIndex(
344 defaults: scratch,
345 historyLocation: historyLocation
346 ).count,
347 Self.proPlusCap
348 )
349 }
350
178 // MARK: Validation at the cap 351 // MARK: Validation at the cap
179 352
180 func testValidationAcceptsAStoreAtTheCap() throws { 353 func testValidationAcceptsAStoreAtTheCap() throws {
181 let saved = entries(Self.proPlusCap) 354 let saved = entries(Self.proPlusCap)
182 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch) 355 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch, historyLocation: historyLocation)
183 356
184 let backup = try DomainDataPortabilityService.backupData(defaults: scratch) 357 let backup = try DomainDataPortabilityService.backupData(defaults: scratch, historyLocation: historyLocation)
185 let report = try DomainDataPortabilityService.validateBackup(data: backup) 358 let report = try DomainDataPortabilityService.validateBackup(data: backup)
186 359
187 XCTAssertTrue(report.errors.isEmpty, "a store at the Pro+ cap failed validation: \(report.errors)") 360 XCTAssertTrue(report.errors.isEmpty, "a store at the Pro+ cap failed validation: \(report.errors)")
LocalAPIService.swift +3 −3
@@ -663,7 +663,7 @@ struct LocalAPIRequestHandler {
663 663
664 private func buildPortfolioSummary() -> PortfolioSummary { 664 private func buildPortfolioSummary() -> PortfolioSummary {
665 let trackedDomains = DomainDataPortabilityService.loadTrackedDomains() 665 let trackedDomains = DomainDataPortabilityService.loadTrackedDomains()
666 let history = DomainDataPortabilityService.loadHistoryEntries() 666 let history = DomainDataPortabilityService.loadHistoryEntries(historyLocation: .default)
667 667
668 var healthyCount = 0 668 var healthyCount = 0
669 var warningCount = 0 669 var warningCount = 0
@@ -743,13 +743,13 @@ struct LocalAPIRequestHandler {
743 743
744 private func historyEntries(for domain: String) -> [HistoryEntry] { 744 private func historyEntries(for domain: String) -> [HistoryEntry] {
745 let normalized = normalizedDomain(domain) 745 let normalized = normalizedDomain(domain)
746 return DomainDataPortabilityService.loadHistoryEntries().filter { 746 return DomainDataPortabilityService.loadHistoryEntries(historyLocation: .default).filter {
747 $0.domain.caseInsensitiveCompare(normalized) == .orderedSame 747 $0.domain.caseInsensitiveCompare(normalized) == .orderedSame
748 } 748 }
749 } 749 }
750 750
751 private func latestHistoryEntry(for domain: String, history: [HistoryEntry]? = nil) -> HistoryEntry? { 751 private func latestHistoryEntry(for domain: String, history: [HistoryEntry]? = nil) -> HistoryEntry? {
752 let entries = history ?? DomainDataPortabilityService.loadHistoryEntries() 752 let entries = history ?? DomainDataPortabilityService.loadHistoryEntries(historyLocation: .default)
753 let normalized = normalizedDomain(domain) 753 let normalized = normalizedDomain(domain)
754 return entries.first { $0.domain.caseInsensitiveCompare(normalized) == .orderedSame } 754 return entries.first { $0.domain.caseInsensitiveCompare(normalized) == .orderedSame }
755 } 755 }