DomainDig/HistoryFileStore.swift

207 lines · 9110 bytes

18 symbols in this file
  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}