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 {
352352/// The policy is documented in `Docs/data-migration.md`.
353353enum DataMigrationService {
354354 /// The schema version this build expects the on-device store to be at.
355 static let currentStoreSchemaVersion = 1
355 static let currentStoreSchemaVersion = 2
356356
357357 /// UserDefaults key holding the store's current schema version.
358358 static let storeSchemaVersionKey = "data.storeSchemaVersion"
@@ -371,7 +371,10 @@ enum DataMigrationService {
371371 return defaults.bool(forKey: legacyNormalizationMarkerKey) ? 1 : 0
372372 }
373373
374 static func migrateIfNeeded(defaults: UserDefaults = .standard) {
374 static func migrateIfNeeded(
375 defaults: UserDefaults = .standard,
376 historyLocation: HistoryFileStore.Location
377 ) {
375378 // At or ahead of this build's version: nothing to do, and never rewrite
376379 // a store a newer build may have reshaped (forward compatibility).
377380 guard storeSchemaVersion(defaults: defaults) < currentStoreSchemaVersion else { return }
@@ -379,31 +382,74 @@ enum DataMigrationService {
379382 var version = storeSchemaVersion(defaults: defaults)
380383 while version < currentStoreSchemaVersion {
381384 let target = version + 1
382 runMigration(to: target, defaults: defaults)
385 runMigration(to: target, defaults: defaults, historyLocation: historyLocation)
383386 defaults.set(target, forKey: storeSchemaVersionKey)
384387 version = target
385388 }
386389 }
387390
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 ) {
389396 switch version {
390397 case 1:
391 normalizeAllStores(defaults: defaults)
398 normalizeAllStores(defaults: defaults, historyLocation: historyLocation)
399 case 2:
400 moveHistoryToFiles(defaults: defaults, historyLocation: historyLocation)
392401 default:
393402 break
394403 }
395404 }
396405
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
397433 /// v1: load every store through its deduplicating loader and write it back.
398434 /// This consolidates duplicate rows, drops the legacy `watchedDomains` key
399435 /// (via `saveTrackedDomains`), and sanitizes monitoring settings against the
400436 /// 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 ) {
402441 let trackedDomains = DomainDataPortabilityService.loadTrackedDomains(defaults: defaults)
403442 DomainDataPortabilityService.saveTrackedDomains(trackedDomains, defaults: defaults)
404443
405 let historyEntries = DomainDataPortabilityService.loadHistoryEntries(defaults: defaults)
406 DomainDataPortabilityService.saveHistoryEntries(historyEntries, defaults: defaults)
444 let historyEntries = DomainDataPortabilityService.loadHistoryEntries(
445 defaults: defaults,
446 historyLocation: historyLocation
447 )
448 DomainDataPortabilityService.saveHistoryEntries(
449 historyEntries,
450 defaults: defaults,
451 historyLocation: historyLocation
452 )
407453
408454 let auditSessions = DomainDataPortabilityService.loadAuditSessions(defaults: defaults)
409455 DomainDataPortabilityService.saveAuditSessions(auditSessions, defaults: defaults)
@@ -601,7 +647,19 @@ enum DomainDataPortabilityService {
601647 defaults.removeObject(forKey: StorageKey.legacyWatchedDomains)
602648 }
603649
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
605663 guard let data = defaults.data(forKey: StorageKey.history) else { return [] }
606664
607665 if let entries = try? JSONDecoder().decode([HistoryEntry].self, from: data) {
@@ -623,12 +681,89 @@ enum DomainDataPortabilityService {
623681 return deduplicatedHistoryEntries(entries)
624682 }
625683
626 static func saveHistoryEntries(_ historyEntries: [HistoryEntry], defaults: UserDefaults = .standard) {
627 if let data = try? JSONEncoder().encode(deduplicatedHistoryEntries(historyEntries)) {
628 defaults.set(data, forKey: StorageKey.history)
629 }
684 /// Rewrites the whole store. This is the migration, a backup import and an
685 /// explicit prune — the cases that really do change every row. A single new
686 /// snapshot should go through `appendHistoryEntry`, which costs 23 ms at
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)
630731 }
631732
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
632767 static func loadAuditSessions(defaults: UserDefaults = .standard) -> [AuditSession] {
633768 guard let data = defaults.data(forKey: StorageKey.audits),
634769 let sessions = try? JSONDecoder().decode([AuditSession].self, from: data) else {
@@ -719,14 +854,17 @@ enum DomainDataPortabilityService {
719854 }
720855 }
721856
722 static func currentBackup(defaults: UserDefaults = .standard) -> DomainDigBackup {
723 DataMigrationService.migrateIfNeeded(defaults: defaults)
857 static func currentBackup(
858 defaults: UserDefaults = .standard,
859 historyLocation: HistoryFileStore.Location
860 ) -> DomainDigBackup {
861 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
724862 return DomainDigBackup(
725863 schemaVersion: DomainDigBackup.currentSchemaVersion,
726864 exportedAt: Date(),
727865 appVersion: AppVersion.current,
728866 trackedDomains: loadTrackedDomains(defaults: defaults),
729 historyEntries: loadHistoryEntries(defaults: defaults),
867 historyEntries: loadHistoryEntries(defaults: defaults, historyLocation: historyLocation),
730868 auditSessions: loadAuditSessions(defaults: defaults),
731869 workflows: loadWorkflows(defaults: defaults),
732870 monitoringSettings: loadMonitoringSettings(defaults: defaults),
@@ -736,8 +874,11 @@ enum DomainDataPortabilityService {
736874 )
737875 }
738876
739 static func backupData(defaults: UserDefaults = .standard) throws -> Data {
740 try makeEncoder().encode(currentBackup(defaults: defaults))
877 static func backupData(
878 defaults: UserDefaults = .standard,
879 historyLocation: HistoryFileStore.Location
880 ) throws -> Data {
881 try makeEncoder().encode(currentBackup(defaults: defaults, historyLocation: historyLocation))
741882 }
742883
743884 static func trackedDomainsExportData(defaults: UserDefaults = .standard) throws -> Data {
@@ -762,13 +903,16 @@ enum DomainDataPortabilityService {
762903 )
763904 }
764905
765 static func historyExportData(defaults: UserDefaults = .standard) throws -> Data {
906 static func historyExportData(
907 defaults: UserDefaults = .standard,
908 historyLocation: HistoryFileStore.Location
909 ) throws -> Data {
766910 try makeEncoder().encode(
767911 HistoryExport(
768912 schemaVersion: DomainDigBackup.currentSchemaVersion,
769913 exportedAt: Date(),
770914 appVersion: AppVersion.current,
771 historyEntries: loadHistoryEntries(defaults: defaults)
915 historyEntries: loadHistoryEntries(defaults: defaults, historyLocation: historyLocation)
772916 )
773917 )
774918 }
@@ -785,13 +929,19 @@ enum DomainDataPortabilityService {
785929 data: Data,
786930 fileName: String,
787931 mode: DataPortabilityImportMode,
788 defaults: UserDefaults = .standard
932 defaults: UserDefaults = .standard,
933 historyLocation: HistoryFileStore.Location
789934 ) throws -> DataImportPreview {
790 DataMigrationService.migrateIfNeeded(defaults: defaults)
791 let currentCounts = lifecycleSummary(defaults: defaults)
935 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
936 let currentCounts = lifecycleSummary(defaults: defaults, historyLocation: historyLocation)
792937
793938 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 )
795945
796946 return DataImportPreview(
797947 fileName: fileName,
@@ -808,11 +958,12 @@ enum DomainDataPortabilityService {
808958 static func applyImport(
809959 _ preview: DataImportPreview,
810960 mode: DataPortabilityImportMode,
811 defaults: UserDefaults = .standard
961 defaults: UserDefaults = .standard,
962 historyLocation: HistoryFileStore.Location
812963 ) throws -> DataImportResult {
813964 switch preview.payload {
814965 case .backup(let backup, let report):
815 try applyBackup(backup, mode: mode, defaults: defaults)
966 try applyBackup(backup, mode: mode, defaults: defaults, historyLocation: historyLocation)
816967 return DataImportResult(
817968 kind: .backup,
818969 mode: mode,
@@ -849,7 +1000,10 @@ enum DomainDataPortabilityService {
8491000 }
8501001 }
8511002
852 static func lifecycleSummary(defaults: UserDefaults = .standard) -> DataLifecycleSummary {
1003 static func lifecycleSummary(
1004 defaults: UserDefaults = .standard,
1005 historyLocation: HistoryFileStore.Location
1006 ) -> DataLifecycleSummary {
8531007 let appSettings = loadAppSettings(defaults: defaults)
8541008 let featureMetadata = loadFeatureMetadata(defaults: defaults)
8551009 let cachedItems = appSettings.recentSearches.count
@@ -857,7 +1011,7 @@ enum DomainDataPortabilityService {
8571011
8581012 return DataLifecycleSummary(
8591013 trackedDomains: loadTrackedDomains(defaults: defaults).count,
860 historySnapshots: loadHistoryEntries(defaults: defaults).count,
1014 historySnapshots: loadHistoryEntries(defaults: defaults, historyLocation: historyLocation).count,
8611015 auditSessions: loadAuditSessions(defaults: defaults).count,
8621016 workflows: loadWorkflows(defaults: defaults).count,
8631017 cachedItems: cachedItems,
@@ -955,11 +1109,16 @@ enum DomainDataPortabilityService {
9551109 private static func applyBackup(
9561110 _ backup: DomainDigBackup,
9571111 mode: DataPortabilityImportMode,
958 defaults: UserDefaults
1112 defaults: UserDefaults,
1113 historyLocation: HistoryFileStore.Location
9591114 ) throws {
9601115 if mode == .replace {
9611116 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 )
9631122 saveAuditSessions(backup.auditSessions ?? [], defaults: defaults)
9641123 saveWorkflows(deduplicatedWorkflows(backup.workflows), defaults: defaults)
9651124 saveMonitoringSettings(
@@ -979,11 +1138,12 @@ enum DomainDataPortabilityService {
9791138 let mergedTrackedDomains = mergeTrackedDomains(existing: existingTrackedDomains, incoming: backup.trackedDomains)
9801139 saveTrackedDomains(mergedTrackedDomains.domains, defaults: defaults)
9811140
982 let existingHistoryEntries = loadHistoryEntries(defaults: defaults)
1141 let existingHistoryEntries = loadHistoryEntries(defaults: defaults, historyLocation: historyLocation)
9831142 let remappedIncomingHistory = backup.historyEntries.map { remapHistoryEntry($0, using: mergedTrackedDomains.idMap) }
9841143 saveHistoryEntries(
9851144 mergeHistoryEntries(existing: existingHistoryEntries, incoming: remappedIncomingHistory),
986 defaults: defaults
1145 defaults: defaults,
1146 historyLocation: historyLocation
9871147 )
9881148
9891149 let existingAuditSessions = loadAuditSessions(defaults: defaults)
@@ -1050,9 +1210,10 @@ enum DomainDataPortabilityService {
10501210 private static func projectCounts(
10511211 for payload: ImportPayload,
10521212 mode: DataPortabilityImportMode,
1053 defaults: UserDefaults
1213 defaults: UserDefaults,
1214 historyLocation: HistoryFileStore.Location
10541215 ) -> DataLifecycleSummary {
1055 let current = lifecycleSummary(defaults: defaults)
1216 let current = lifecycleSummary(defaults: defaults, historyLocation: historyLocation)
10561217 switch payload {
10571218 case .backup(let backup, _):
10581219 if mode == .replace {
@@ -1068,7 +1229,7 @@ enum DomainDataPortabilityService {
10681229
10691230 return DataLifecycleSummary(
10701231 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,
10721233 auditSessions: mergeAuditSessions(existing: loadAuditSessions(defaults: defaults), incoming: backup.auditSessions ?? []).count,
10731234 workflows: mergeWorkflows(existing: loadWorkflows(defaults: defaults), incoming: backup.workflows).count,
10741235 cachedItems: max(current.cachedItems, backup.appSettings.recentSearches.count),
DomainDig/DataResetService.swift +6
@@ -47,6 +47,12 @@ enum DataResetService {
4747
4848 try removeTemporaryFiles()
4949
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
5056 let defaults = UserDefaults.standard
5157 defaults.removePersistentDomain(forName: bundleIdentifier)
5258 defaults.synchronize()
DomainDig/DomainMonitoringService.swift +20 −8
@@ -18,7 +18,7 @@ enum MonitoringStorage {
1818 static let maxLogs = 40
1919
2020 static func loadSettings(defaults: UserDefaults = .standard) -> MonitoringSettings {
21 DataMigrationService.migrateIfNeeded(defaults: defaults)
21 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: .default)
2222 return DomainDataPortabilityService.loadMonitoringSettings(defaults: defaults)
2323 }
2424
@@ -27,7 +27,7 @@ enum MonitoringStorage {
2727 }
2828
2929 static func loadLogs(defaults: UserDefaults = .standard) -> [MonitoringLog] {
30 DataMigrationService.migrateIfNeeded(defaults: defaults)
30 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: .default)
3131 return DomainDataPortabilityService.loadMonitoringLogs(defaults: defaults)
3232 }
3333
@@ -36,7 +36,7 @@ enum MonitoringStorage {
3636 }
3737
3838 static func loadTrackedDomains(defaults: UserDefaults = .standard) -> [TrackedDomain] {
39 DataMigrationService.migrateIfNeeded(defaults: defaults)
39 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: .default)
4040 return DomainDataPortabilityService.loadTrackedDomains(defaults: defaults)
4141 }
4242
@@ -44,13 +44,25 @@ enum MonitoringStorage {
4444 DomainDataPortabilityService.saveTrackedDomains(domains, defaults: defaults)
4545 }
4646
47 static func loadHistoryEntries(defaults: UserDefaults = .standard) -> [HistoryEntry] {
48 DataMigrationService.migrateIfNeeded(defaults: defaults)
49 return DomainDataPortabilityService.loadHistoryEntries(defaults: defaults)
47 /// The background monitoring run has no view model, so the real store is
48 /// the right one here. Stated rather than defaulted: every other history
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 )
5059 }
5160
52 static func saveHistoryEntries(_ entries: [HistoryEntry]) {
53 DomainDataPortabilityService.saveHistoryEntries(entries)
61 static func saveHistoryEntries(
62 _ entries: [HistoryEntry],
63 historyLocation: HistoryFileStore.Location = .default
64 ) {
65 DomainDataPortabilityService.saveHistoryEntries(entries, historyLocation: historyLocation)
5466 }
5567
5668 static func sanitizeSettings(_ settings: MonitoringSettings, trackedDomains: [TrackedDomain]) -> MonitoringSettings {
DomainDig/DomainViewModel+Export.swift +15 −4
@@ -59,7 +59,7 @@ extension DomainViewModel {
5959 }
6060
6161 func exportFullBackupData() -> Data? {
62 try? DomainDataPortabilityService.backupData(defaults: defaults)
62 try? DomainDataPortabilityService.backupData(defaults: defaults, historyLocation: historyLocation)
6363 }
6464
6565 func exportPortableTrackedDomainsJSONData() -> Data? {
@@ -79,7 +79,7 @@ extension DomainViewModel {
7979 }
8080
8181 func exportPortableHistoryJSONData() -> Data? {
82 try? DomainDataPortabilityService.historyExportData(defaults: defaults)
82 try? DomainDataPortabilityService.historyExportData(defaults: defaults, historyLocation: historyLocation)
8383 }
8484
8585 func prepareDataImport(
@@ -87,11 +87,22 @@ extension DomainViewModel {
8787 fileName: String,
8888 mode: DataPortabilityImportMode
8989 ) 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 )
9197 }
9298
9399 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 )
95106 refreshPersistedData()
96107 portabilityStatusMessage = result.summary
97108 CloudSyncService.shared.markAppSettingsChanged()
DomainDig/DomainViewModel+Workflows.swift +1 −1
@@ -132,7 +132,7 @@ extension DomainViewModel {
132132 }
133133
134134 func refreshWorkflowList() async {
135 workflows = Self.loadWorkflows(defaults: defaults)
135 workflows = Self.loadWorkflows(defaults: defaults, historyLocation: historyLocation)
136136 await Task.yield()
137137 }
138138}
DomainDig/DomainViewModel.swift +112 −36
@@ -342,17 +342,25 @@ final class DomainViewModel {
342342 /// one the app is using.
343343 let defaults: UserDefaults
344344
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 ) {
346353 self.defaults = defaults
354 self.historyLocation = historyLocation
347355 recentSearches = DomainDataPortabilityService.loadRecentSearches(defaults: defaults)
348 trackedDomains = DomainViewModel.loadTrackedDomains(defaults: defaults)
349 history = DomainViewModel.loadHistoryEntries(defaults: defaults)
356 trackedDomains = DomainViewModel.loadTrackedDomains(defaults: defaults, historyLocation: historyLocation)
357 history = DomainViewModel.loadHistoryEntries(defaults: defaults, historyLocation: historyLocation)
350358 auditSessions = DomainDataPortabilityService.loadAuditSessions(defaults: defaults)
351 workflows = DomainViewModel.loadWorkflows(defaults: defaults)
359 workflows = DomainViewModel.loadWorkflows(defaults: defaults, historyLocation: historyLocation)
352360 watchlistSavedViews = DomainViewModel.loadWatchlistSavedViews(defaults: defaults)
353361 monitoringSettings = MonitoringStorage.loadSettings(defaults: defaults)
354362 monitoringLogs = MonitoringStorage.loadLogs(defaults: defaults)
355 dataLifecycleSummary = DomainDataPortabilityService.lifecycleSummary(defaults: defaults)
363 dataLifecycleSummary = DomainDataPortabilityService.lifecycleSummary(defaults: defaults, historyLocation: historyLocation)
356364 historyAutoPruneOption = DomainViewModel.loadHistoryAutoPruneOption(defaults: defaults)
357365 }
358366
@@ -843,13 +851,15 @@ final class DomainViewModel {
843851 let ids = removedDomains.map(\.id)
844852 CloudSyncService.shared.recordTrackedDomainReset(removedDomains)
845853 trackedDomains.removeAll { ids.contains($0.id) }
854 var relinked: [HistoryEntry] = []
846855 history.indices.forEach { index in
847856 if let trackedDomainID = history[index].trackedDomainID, ids.contains(trackedDomainID) {
848857 history[index].trackedDomainID = nil
858 relinked.append(history[index])
849859 }
850860 }
851861 persistTrackedDomains()
852 persistHistory()
862 relinked.forEach { storeHistoryEntry($0, replacingExisting: true) }
853863 sanitizeMonitoringSelection()
854864 }
855865
@@ -857,13 +867,15 @@ final class DomainViewModel {
857867 guard canDelete(trackedDomain) else { return }
858868 CloudSyncService.shared.recordTrackedDomainDeletion(trackedDomain)
859869 trackedDomains.removeAll { $0.id == trackedDomain.id }
870 var relinked: [HistoryEntry] = []
860871 history.indices.forEach { index in
861872 if history[index].trackedDomainID == trackedDomain.id {
862873 history[index].trackedDomainID = nil
874 relinked.append(history[index])
863875 }
864876 }
865877 persistTrackedDomains()
866 persistHistory()
878 relinked.forEach { storeHistoryEntry($0, replacingExisting: true) }
867879 sanitizeMonitoringSelection()
868880 }
869881
@@ -948,18 +960,23 @@ final class DomainViewModel {
948960 }
949961
950962 func removeHistoryEntries(at offsets: IndexSet) {
963 let removed = Set(offsets.map { history[$0].id })
951964 history.remove(atOffsets: offsets)
952 persistHistory()
965 removeStoredHistory(ids: removed)
953966 }
954967
955968 func removeHistoryEntries(withIDs ids: [UUID]) {
956969 history.removeAll { ids.contains($0.id) }
957 persistHistory()
970 removeStoredHistory(ids: Set(ids))
958971 }
959972
960973 func clearHistory() {
961974 history.removeAll()
962 persistHistory()
975 DomainDataPortabilityService.removeAllHistoryEntries(
976 defaults: defaults,
977 historyLocation: historyLocation
978 )
979 refreshDataLifecycleSummary()
963980 clearMonitoringLogs()
964981 refreshDataLifecycleSummary()
965982 }
@@ -1001,9 +1018,9 @@ final class DomainViewModel {
10011018 // scene activation); the disk reload below would wipe the fixtures.
10021019 if auditFixturesActive { return }
10031020 #endif
1004 DataMigrationService.migrateIfNeeded(defaults: defaults)
1005 trackedDomains = Self.loadTrackedDomains(defaults: defaults)
1006 history = Self.loadHistoryEntries(defaults: defaults)
1021 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
1022 trackedDomains = Self.loadTrackedDomains(defaults: defaults, historyLocation: historyLocation)
1023 history = Self.loadHistoryEntries(defaults: defaults, historyLocation: historyLocation)
10071024 monitoringSettings = MonitoringStorage.sanitizeSettings(
10081025 MonitoringStorage.loadSettings(defaults: defaults),
10091026 trackedDomains: trackedDomains
@@ -1014,7 +1031,7 @@ final class DomainViewModel {
10141031 }
10151032
10161033 func refreshDataLifecycleSummary() {
1017 dataLifecycleSummary = DomainDataPortabilityService.lifecycleSummary(defaults: defaults)
1034 dataLifecycleSummary = DomainDataPortabilityService.lifecycleSummary(defaults: defaults, historyLocation: historyLocation)
10181035 }
10191036
10201037 func refreshPersistedData() {
@@ -1023,10 +1040,10 @@ final class DomainViewModel {
10231040 if auditFixturesActive { return }
10241041 #endif
10251042 recentSearches = DomainDataPortabilityService.loadRecentSearches(defaults: defaults)
1026 trackedDomains = Self.loadTrackedDomains(defaults: defaults)
1027 history = Self.loadHistoryEntries(defaults: defaults)
1043 trackedDomains = Self.loadTrackedDomains(defaults: defaults, historyLocation: historyLocation)
1044 history = Self.loadHistoryEntries(defaults: defaults, historyLocation: historyLocation)
10281045 auditSessions = DomainDataPortabilityService.loadAuditSessions(defaults: defaults)
1029 workflows = Self.loadWorkflows(defaults: defaults)
1046 workflows = Self.loadWorkflows(defaults: defaults, historyLocation: historyLocation)
10301047 monitoringSettings = MonitoringStorage.sanitizeSettings(
10311048 MonitoringStorage.loadSettings(defaults: defaults),
10321049 trackedDomains: trackedDomains
@@ -1792,7 +1809,10 @@ final class DomainViewModel {
17921809 currentHistoryEntryID = entry.id
17931810 }
17941811
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 {
17961816 history[0] = entry
17971817 } else {
17981818 history.insert(entry, at: 0)
@@ -1809,18 +1829,59 @@ final class DomainViewModel {
18091829 certificateWarningLevel: DomainDiffService.certificateWarningLevel(for: snapshot),
18101830 certificateDaysRemaining: snapshot.sslInfo?.daysUntilExpiry
18111831 )
1812 persistHistory()
1832 storeHistoryEntry(entry, replacingExisting: replacedLatest)
18131833 notifyIfNeeded(for: entry, snapshot: snapshot, previousSnapshot: previousSnapshot)
18141834 return entry
18151835 }
18161836
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`.
18171878 private func persistHistory() {
18181879 if historyPersistenceSuspended {
18191880 historyPersistenceDirty = true
18201881 return
18211882 }
18221883 let persistStartedAt = DomainDebugLog.signpostStart("DomainViewModel.persistHistory")
1823 DomainDataPortabilityService.saveHistoryEntries(history, defaults: defaults)
1884 DomainDataPortabilityService.saveHistoryEntries(history, defaults: defaults, historyLocation: historyLocation)
18241885 refreshDataLifecycleSummary()
18251886 DomainDebugLog.signpostEnd("DomainViewModel.persistHistory", start: persistStartedAt, extra: "count=\(history.count)")
18261887 }
@@ -1840,7 +1901,7 @@ final class DomainViewModel {
18401901 func updateHistoryNote(_ note: String, for entry: HistoryEntry) {
18411902 guard let index = history.firstIndex(where: { $0.id == entry.id }) else { return }
18421903 history[index].note = note.trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty
1843 persistHistory()
1904 storeHistoryEntry(history[index], replacingExisting: true)
18441905 }
18451906
18461907 #if DEBUG
@@ -1891,15 +1952,20 @@ final class DomainViewModel {
18911952
18921953 if historyPersistenceDirty {
18931954 historyPersistenceDirty = false
1894 DomainDataPortabilityService.saveHistoryEntries(history, defaults: defaults)
1955 DomainDataPortabilityService.saveHistoryEntries(history, defaults: defaults, historyLocation: historyLocation)
18951956 }
18961957
18971958 refreshDataLifecycleSummary()
18981959 }
18991960
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
19001967 private func trimHistoryToLimit() {
1901 let hardLimit = historyAutoPruneOption.keepCount ?? Self.maxHistory
1902 history = Array(history.prefix(min(hardLimit, Self.maxHistory)))
1968 history = Array(history.prefix(effectiveHistoryLimit))
19031969 }
19041970
19051971 private func nextSnapshotIndex(for domain: String, trackedDomainID: UUID?) -> Int {
@@ -2024,18 +2090,16 @@ final class DomainViewModel {
20242090
20252091 private func linkTrackedDomainHistory(for domain: String) {
20262092 guard let trackedDomain = trackedDomain(for: domain) else { return }
2027 var didChange = false
20282093
2094 var relinked: [HistoryEntry] = []
20292095 for index in history.indices where history[index].domain.caseInsensitiveCompare(domain) == .orderedSame {
20302096 if history[index].trackedDomainID != trackedDomain.id {
20312097 history[index].trackedDomainID = trackedDomain.id
2032 didChange = true
2098 relinked.append(history[index])
20332099 }
20342100 }
20352101
2036 if didChange {
2037 persistHistory()
2038 }
2102 relinked.forEach { storeHistoryEntry($0, replacingExisting: true) }
20392103
20402104 if let latestEntry = history.first(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }),
20412105 let trackedIndex = trackedDomains.firstIndex(where: { $0.id == trackedDomain.id }) {
@@ -3013,9 +3077,15 @@ final class DomainViewModel {
30133077 )
30143078 }
30153079
3016 private static func loadHistoryEntries(defaults: UserDefaults) -> [HistoryEntry] {
3017 DataMigrationService.migrateIfNeeded(defaults: defaults)
3018 return DomainDataPortabilityService.loadHistoryEntries(defaults: defaults)
3080 private static func loadHistoryEntries(
3081 defaults: UserDefaults,
3082 historyLocation: HistoryFileStore.Location
3083 ) -> [HistoryEntry] {
3084 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
3085 return DomainDataPortabilityService.loadHistoryEntries(
3086 defaults: defaults,
3087 historyLocation: historyLocation
3088 )
30193089 }
30203090
30213091 private static func loadHistoryAutoPruneOption(defaults: UserDefaults) -> HistoryAutoPruneOption {
@@ -3026,8 +3096,11 @@ final class DomainViewModel {
30263096 return option
30273097 }
30283098
3029 private static func loadTrackedDomains(defaults: UserDefaults) -> [TrackedDomain] {
3030 DataMigrationService.migrateIfNeeded(defaults: defaults)
3099 private static func loadTrackedDomains(
3100 defaults: UserDefaults,
3101 historyLocation: HistoryFileStore.Location
3102 ) -> [TrackedDomain] {
3103 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
30313104 return DomainDataPortabilityService.loadTrackedDomains(defaults: defaults)
30323105 }
30333106
@@ -3037,8 +3110,11 @@ final class DomainViewModel {
30373110 refreshDataLifecycleSummary()
30383111 }
30393112
3040 static func loadWorkflows(defaults: UserDefaults) -> [DomainWorkflow] {
3041 DataMigrationService.migrateIfNeeded(defaults: defaults)
3113 static func loadWorkflows(
3114 defaults: UserDefaults,
3115 historyLocation: HistoryFileStore.Location
3116 ) -> [DomainWorkflow] {
3117 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
30423118 return DomainDataPortabilityService.loadWorkflows(defaults: defaults)
30433119 }
30443120
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 {
116116 return ScheduledReportOutcome(success: false, message: "No tracked domains to report on.", log: nil)
117117 }
118118
119 let history = DomainDataPortabilityService.loadHistoryEntries()
119 let history = DomainDataPortabilityService.loadHistoryEntries(historyLocation: .default)
120120 let builder = DomainReportBuilder()
121121 let reports = trackedDomains.compactMap { trackedDomain -> DomainReport? in
122122 let entry = history.first { entry in
DomainDigTests/DataMigrationServiceTests.swift +21 −8
@@ -14,22 +14,31 @@ final class DataMigrationServiceTests: XCTestCase {
1414 private var defaults: UserDefaults!
1515 private let base = Date(timeIntervalSince1970: 1_700_000_000)
1616
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
1721 override func setUp() {
1822 super.setUp()
1923 defaults = UserDefaults(suiteName: suiteName)
2024 defaults.removePersistentDomain(forName: suiteName)
25 historyLocation = HistoryFileStore.Location(
26 root: URL(fileURLWithPath: NSTemporaryDirectory())
27 .appendingPathComponent("DomainDigMigrationTest-\(UUID().uuidString)", isDirectory: true)
28 )
2129 }
2230
2331 override func tearDown() {
2432 defaults.removePersistentDomain(forName: suiteName)
2533 defaults = nil
34 HistoryFileStore.removeAll(at: historyLocation)
2635 super.tearDown()
2736 }
2837
2938 func testFreshStoreIsStampedAtCurrentVersion() {
3039 XCTAssertEqual(DataMigrationService.storeSchemaVersion(defaults: defaults), 0)
3140
32 DataMigrationService.migrateIfNeeded(defaults: defaults)
41 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
3342
3443 XCTAssertEqual(
3544 DataMigrationService.storeSchemaVersion(defaults: defaults),
@@ -41,13 +50,17 @@ final class DataMigrationServiceTests: XCTestCase {
4150 let legacy = [WatchedDomain(domain: "legacy.example", createdAt: base, lastKnownAvailability: .registered)]
4251 defaults.set(try JSONEncoder().encode(legacy), forKey: "watchedDomains")
4352
44 DataMigrationService.migrateIfNeeded(defaults: defaults)
53 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
4554
4655 let tracked = DomainDataPortabilityService.loadTrackedDomains(defaults: defaults)
4756 XCTAssertEqual(tracked.map(\.domain), ["legacy.example"])
4857 XCTAssertNil(defaults.data(forKey: "watchedDomains"), "legacy key is dropped after migration")
4958 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 )
5164 }
5265
5366 func testMigrationDeduplicatesTheStoredBlobInPlace() throws {
@@ -57,7 +70,7 @@ final class DataMigrationServiceTests: XCTestCase {
5770 ]
5871 defaults.set(try JSONEncoder().encode(dupes), forKey: "trackedDomains")
5972
60 DataMigrationService.migrateIfNeeded(defaults: defaults)
73 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
6174
6275 let data = try XCTUnwrap(defaults.data(forKey: "trackedDomains"))
6376 let stored = try JSONDecoder().decode([TrackedDomain].self, from: data)
@@ -70,10 +83,10 @@ final class DataMigrationServiceTests: XCTestCase {
7083 forKey: "trackedDomains"
7184 )
7285
73 DataMigrationService.migrateIfNeeded(defaults: defaults)
86 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
7487 let afterFirst = defaults.data(forKey: "trackedDomains")
7588
76 DataMigrationService.migrateIfNeeded(defaults: defaults)
89 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
7790 let afterSecond = defaults.data(forKey: "trackedDomains")
7891
7992 XCTAssertEqual(afterFirst, afterSecond, "a second run makes no further changes")
@@ -91,7 +104,7 @@ final class DataMigrationServiceTests: XCTestCase {
91104 // Already at v1, so the v1 step must not re-run: a leftover legacy blob
92105 // is left exactly as found.
93106 defaults.set(Data("x".utf8), forKey: "watchedDomains")
94 DataMigrationService.migrateIfNeeded(defaults: defaults)
107 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
95108 XCTAssertNotNil(defaults.data(forKey: "watchedDomains"), "v1 is treated as already applied; no re-run")
96109 }
97110
@@ -101,7 +114,7 @@ final class DataMigrationServiceTests: XCTestCase {
101114 let blob = try JSONEncoder().encode([TrackedDomain(domain: "keep.example", updatedAt: base)])
102115 defaults.set(blob, forKey: "trackedDomains")
103116
104 DataMigrationService.migrateIfNeeded(defaults: defaults)
117 DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
105118
106119 XCTAssertEqual(DataMigrationService.storeSchemaVersion(defaults: defaults), future, "must never downgrade")
107120 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 {
1313 private var suiteName = ""
1414 private var scratch = UserDefaults.standard
1515
16 /// History lives in a directory now, so the scratch store has two halves.
17 private var historyLocation = HistoryFileStore.Location.default
18
1619 override func setUpWithError() throws {
1720 try super.setUpWithError()
1821 suiteName = "net.cleberg.DomainDig.tests.\(UUID().uuidString)"
1922 scratch = try XCTUnwrap(UserDefaults(suiteName: suiteName))
23 historyLocation = HistoryFileStore.Location(
24 root: URL(fileURLWithPath: NSTemporaryDirectory())
25 .appendingPathComponent("DomainDigVMTest-\(UUID().uuidString)", isDirectory: true)
26 )
2027 }
2128
2229 override func tearDown() {
2330 UserDefaults.standard.removePersistentDomain(forName: suiteName)
31 HistoryFileStore.removeAll(at: historyLocation)
2432 super.tearDown()
2533 }
2634
@@ -32,7 +40,7 @@ final class DomainViewModelStoreTests: XCTestCase {
3240 private static var retained: [DomainViewModel] = []
3341
3442 private func makeViewModel() -> DomainViewModel {
35 let viewModel = DomainViewModel(defaults: scratch)
43 let viewModel = DomainViewModel(defaults: scratch, historyLocation: historyLocation)
3644 Self.retained.append(viewModel)
3745 return viewModel
3846 }
@@ -68,7 +76,7 @@ final class DomainViewModelStoreTests: XCTestCase {
6876 [TrackedDomain(domain: "tracked.example", createdAt: Date(), updatedAt: Date())],
6977 defaults: scratch
7078 )
71 DomainDataPortabilityService.saveHistoryEntries(makeEntries(3), defaults: scratch)
79 DomainDataPortabilityService.saveHistoryEntries(makeEntries(3), defaults: scratch, historyLocation: historyLocation)
7280
7381 let viewModel = makeViewModel()
7482
@@ -98,7 +106,7 @@ final class DomainViewModelStoreTests: XCTestCase {
98106 let other = try XCTUnwrap(UserDefaults(suiteName: otherName))
99107
100108 let first = makeViewModel()
101 let second = DomainViewModel(defaults: other)
109 let second = DomainViewModel(defaults: other, historyLocation: historyLocation)
102110 Self.retained.append(second)
103111
104112 first.addRecentSearch("first.example")
@@ -142,7 +150,7 @@ final class DomainViewModelStoreTests: XCTestCase {
142150 viewModel.setHistoryAutoPruneOption(.keep50)
143151
144152 XCTAssertEqual(viewModel.history.count, 50)
145 XCTAssertEqual(DomainDataPortabilityService.loadHistoryEntries(defaults: scratch).count, 50)
153 XCTAssertEqual(DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation).count, 50)
146154 }
147155
148156 /// Pruning trims from the front, so the rows kept must be the newest ones.
@@ -172,7 +180,7 @@ final class DomainViewModelStoreTests: XCTestCase {
172180 /// A store already over the cap must still be readable. Pruning happens on
173181 /// a write, not on a read, so loading must not drop rows.
174182 func testAStoreAlreadyOverTheCapLoadsEveryRow() {
175 DomainDataPortabilityService.saveHistoryEntries(makeEntries(300), defaults: scratch)
183 DomainDataPortabilityService.saveHistoryEntries(makeEntries(300), defaults: scratch, historyLocation: historyLocation)
176184
177185 XCTAssertEqual(makeViewModel().history.count, 300)
178186 }
DomainDigTests/HistoryEntryCodableTests.swift +15 −2
@@ -126,8 +126,21 @@ final class HistoryEntryCodableTests: XCTestCase {
126126 let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
127127 defer { defaults.removePersistentDomain(forName: suite) }
128128
129 DomainDataPortabilityService.saveHistoryEntries([makeEntry()], defaults: defaults)
130 let loaded = DomainDataPortabilityService.loadHistoryEntries(defaults: defaults)
129 let historyLocation = HistoryFileStore.Location(
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 )
131144
132145 XCTAssertEqual(loaded.count, 1, "entry was silently dropped by the load path")
133146 XCTAssertEqual(loaded.first?.domain, "example.com")
DomainDigTests/HistoryStoreTests.swift +195 −22
@@ -18,17 +18,31 @@ final class HistoryStoreTests: XCTestCase {
1818 private var suiteName = ""
1919 private var scratch = UserDefaults.standard
2020
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
2126 override func setUpWithError() throws {
2227 try super.setUpWithError()
2328 suiteName = "net.cleberg.DomainDig.tests.\(UUID().uuidString)"
2429 scratch = try XCTUnwrap(UserDefaults(suiteName: suiteName))
30 historyLocation = Self.scratchLocation()
2531 }
2632
2733 override func tearDown() {
2834 UserDefaults.standard.removePersistentDomain(forName: suiteName)
35 HistoryFileStore.removeAll(at: historyLocation)
2936 super.tearDown()
3037 }
3138
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
3246 private func entries(_ count: Int) -> [HistoryEntry] {
3347 (0..<count).map { SnapshotFixture.historyEntry(index: $0) }
3448 }
@@ -38,8 +52,8 @@ final class HistoryStoreTests: XCTestCase {
3852 func testTwoThousandEntriesSurviveASaveAndLoad() {
3953 let saved = entries(Self.proPlusCap)
4054
41 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch)
42 let loaded = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch)
55 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch, historyLocation: historyLocation)
56 let loaded = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
4357
4458 XCTAssertEqual(loaded.count, Self.proPlusCap, "the store dropped or added rows")
4559 XCTAssertEqual(Set(loaded.map(\.id)), Set(saved.map(\.id)), "the store changed which rows exist")
@@ -49,9 +63,9 @@ final class HistoryStoreTests: XCTestCase {
4963 /// history list, the dashboard's recent activity, the diff view's
5064 /// "previous snapshot" — takes that for granted.
5165 func testTheStoreReturnsRowsNewestFirst() {
52 DomainDataPortabilityService.saveHistoryEntries(entries(Self.proPlusCap), defaults: scratch)
66 DomainDataPortabilityService.saveHistoryEntries(entries(Self.proPlusCap), defaults: scratch, historyLocation: historyLocation)
5367
54 let loaded = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch)
68 let loaded = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
5569
5670 XCTAssertEqual(loaded.map(\.timestamp), loaded.map(\.timestamp).sorted(by: >))
5771 XCTAssertEqual(loaded.first?.snapshotIndex, Self.proPlusCap - 1)
@@ -61,10 +75,10 @@ final class HistoryStoreTests: XCTestCase {
6175 func testNoRowIsDuplicatedAcrossRepeatedSaves() {
6276 let saved = entries(Self.proPlusCap)
6377
64 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch)
65 let once = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch)
66 DomainDataPortabilityService.saveHistoryEntries(once, defaults: scratch)
67 let twice = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch)
78 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch, historyLocation: historyLocation)
79 let once = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
80 DomainDataPortabilityService.saveHistoryEntries(once, defaults: scratch, historyLocation: historyLocation)
81 let twice = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
6882
6983 XCTAssertEqual(twice.count, Self.proPlusCap)
7084 XCTAssertEqual(Set(twice.map(\.id)).count, Self.proPlusCap, "a row was duplicated")
@@ -77,9 +91,9 @@ final class HistoryStoreTests: XCTestCase {
7791 func testEveryPopulatedFieldSurvivesTheRoundTrip() throws {
7892 let original = SnapshotFixture.historyEntry(index: 7)
7993
80 DomainDataPortabilityService.saveHistoryEntries([original], defaults: scratch)
94 DomainDataPortabilityService.saveHistoryEntries([original], defaults: scratch, historyLocation: historyLocation)
8195 let restored = try XCTUnwrap(
82 DomainDataPortabilityService.loadHistoryEntries(defaults: scratch).first
96 DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation).first
8397 )
8498
8599 XCTAssertEqual(restored.id, original.id)
@@ -135,23 +149,34 @@ final class HistoryStoreTests: XCTestCase {
135149
136150 func testABackupAtTheCapRestoresEveryRow() throws {
137151 let saved = entries(Self.proPlusCap)
138 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch)
152 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch, historyLocation: historyLocation)
139153
140 let backup = try DomainDataPortabilityService.backupData(defaults: scratch)
154 let backup = try DomainDataPortabilityService.backupData(defaults: scratch, historyLocation: historyLocation)
141155
142156 let restoreName = "net.cleberg.DomainDig.tests.\(UUID().uuidString)"
143157 defer { UserDefaults.standard.removePersistentDomain(forName: restoreName) }
144158 let restoreStore = try XCTUnwrap(UserDefaults(suiteName: restoreName))
159 let restoreLocation = Self.scratchLocation()
160 defer { HistoryFileStore.removeAll(at: restoreLocation) }
145161
146162 let preview = try DomainDataPortabilityService.prepareImport(
147163 data: backup,
148164 fileName: "backup.json",
149165 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
151174 )
152 _ = try DomainDataPortabilityService.applyImport(preview, mode: .replace, defaults: restoreStore)
153175
154 let restored = DomainDataPortabilityService.loadHistoryEntries(defaults: restoreStore)
176 let restored = DomainDataPortabilityService.loadHistoryEntries(
177 defaults: restoreStore,
178 historyLocation: restoreLocation
179 )
155180 XCTAssertEqual(restored.count, Self.proPlusCap, "the backup round trip changed the row count")
156181 XCTAssertEqual(Set(restored.map(\.id)), Set(saved.map(\.id)), "the backup round trip changed which rows exist")
157182 }
@@ -159,29 +184,177 @@ final class HistoryStoreTests: XCTestCase {
159184 /// A merge import of a backup of the same store must not double every row.
160185 func testMergingABackupOfTheSameStoreDoesNotDuplicateRows() throws {
161186 let saved = entries(500)
162 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch)
187 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch, historyLocation: historyLocation)
163188
164 let backup = try DomainDataPortabilityService.backupData(defaults: scratch)
189 let backup = try DomainDataPortabilityService.backupData(defaults: scratch, historyLocation: historyLocation)
165190 let preview = try DomainDataPortabilityService.prepareImport(
166191 data: backup,
167192 fileName: "backup.json",
168193 mode: .merge,
169 defaults: scratch
194 defaults: scratch,
195 historyLocation: historyLocation
170196 )
171 _ = try DomainDataPortabilityService.applyImport(preview, mode: .merge, defaults: scratch)
197 _ = try DomainDataPortabilityService.applyImport(preview, mode: .merge, defaults: scratch, historyLocation: historyLocation)
172198
173 let merged = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch)
199 let merged = DomainDataPortabilityService.loadHistoryEntries(defaults: scratch, historyLocation: historyLocation)
174200 XCTAssertEqual(merged.count, 500, "merging a backup of the same store duplicated rows")
175201 XCTAssertEqual(Set(merged.map(\.id)).count, 500)
176202 }
177203
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
178351 // MARK: Validation at the cap
179352
180353 func testValidationAcceptsAStoreAtTheCap() throws {
181354 let saved = entries(Self.proPlusCap)
182 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch)
355 DomainDataPortabilityService.saveHistoryEntries(saved, defaults: scratch, historyLocation: historyLocation)
183356
184 let backup = try DomainDataPortabilityService.backupData(defaults: scratch)
357 let backup = try DomainDataPortabilityService.backupData(defaults: scratch, historyLocation: historyLocation)
185358 let report = try DomainDataPortabilityService.validateBackup(data: backup)
186359
187360 XCTAssertTrue(report.errors.isEmpty, "a store at the Pro+ cap failed validation: \(report.errors)")
LocalAPIService.swift +3 −3
@@ -663,7 +663,7 @@ struct LocalAPIRequestHandler {
663663
664664 private func buildPortfolioSummary() -> PortfolioSummary {
665665 let trackedDomains = DomainDataPortabilityService.loadTrackedDomains()
666 let history = DomainDataPortabilityService.loadHistoryEntries()
666 let history = DomainDataPortabilityService.loadHistoryEntries(historyLocation: .default)
667667
668668 var healthyCount = 0
669669 var warningCount = 0
@@ -743,13 +743,13 @@ struct LocalAPIRequestHandler {
743743
744744 private func historyEntries(for domain: String) -> [HistoryEntry] {
745745 let normalized = normalizedDomain(domain)
746 return DomainDataPortabilityService.loadHistoryEntries().filter {
746 return DomainDataPortabilityService.loadHistoryEntries(historyLocation: .default).filter {
747747 $0.domain.caseInsensitiveCompare(normalized) == .orderedSame
748748 }
749749 }
750750
751751 private func latestHistoryEntry(for domain: String, history: [HistoryEntry]? = nil) -> HistoryEntry? {
752 let entries = history ?? DomainDataPortabilityService.loadHistoryEntries()
752 let entries = history ?? DomainDataPortabilityService.loadHistoryEntries(historyLocation: .default)
753753 let normalized = normalizedDomain(domain)
754754 return entries.first { $0.domain.caseInsensitiveCompare(normalized) == .orderedSame }
755755 }