DomainDigTests/CloudSyncMergeTests.swift

2ad5d8160338d289a65d6a4d1c214a02bf916f1f
domain-dig/DomainDigTests/CloudSyncMergeTests.swift history · blame · raw

409 lines · 18715 bytes

33 symbols in this file
  1import XCTest
  2@testable import DomainDig
  3
  4/// Sync conflicts used to be decided by `updatedAt` and `deletedAt`, both minted
  5/// by `Date()` on the writing device, so the winner depended on whose clock was
  6/// right. These pin the replacement: CloudKit's server-assigned
  7/// `CKRecord.modificationDate` decides, and the payload dates are only display
  8/// metadata. `CloudSyncService` itself cannot be built in a test — it is a
  9/// `@MainActor` singleton wired to `CKContainer.default()` — so the decisions
 10/// are tested where they live, in `CloudSyncMerge`.
 11final class CloudSyncMergeTests: XCTestCase {
 12
 13    // MARK: Row versus row
 14
 15    func testNewerServerDateWinsTheScalarFields() {
 16        let local = trackedDomainRow("example.com", isPinned: false, serverDate: at(100), deviceDate: at(100))
 17        let remote = trackedDomainRow("example.com", isPinned: true, serverDate: at(200), deviceDate: at(200))
 18
 19        let merged = CloudSyncMerge.mergeTrackedDomains([local], [remote])
 20
 21        XCTAssertEqual(merged.domains.count, 1)
 22        XCTAssertEqual(merged.domains.first?.value.isPinned, true)
 23        XCTAssertTrue(merged.hadConflict)
 24    }
 25
 26    func testNewerServerDateWinsInTheOtherArgumentOrder() {
 27        let older = trackedDomainRow("example.com", isPinned: false, serverDate: at(100), deviceDate: at(100))
 28        let newer = trackedDomainRow("example.com", isPinned: true, serverDate: at(200), deviceDate: at(200))
 29
 30        let merged = CloudSyncMerge.mergeTrackedDomains([newer], [older])
 31
 32        XCTAssertEqual(merged.domains.first?.value.isPinned, true)
 33    }
 34
 35    /// The regression this whole change exists for: a device whose clock runs
 36    /// days fast stamps `updatedAt` in the future, and under the old rule that
 37    /// made it win every conflict it took part in. The server date it was
 38    /// actually saved at is older, so it loses.
 39    func testRemoteRowWithASkewedClockLosesToAnOlderDeviceDateWithANewerServerDate() {
 40        let local = trackedDomainRow("example.com", isPinned: false, serverDate: at(200), deviceDate: at(100))
 41        let skewedRemote = trackedDomainRow("example.com", isPinned: true, serverDate: at(100), deviceDate: at(99_999))
 42
 43        let merged = CloudSyncMerge.mergeTrackedDomains([local], [skewedRemote])
 44
 45        XCTAssertEqual(merged.domains.first?.value.isPinned, false)
 46    }
 47
 48    /// A row this device has edited since its last push has no server date at
 49    /// all. Treating that as older would throw away every edit made offline, so
 50    /// it counts as the more recent of the two.
 51    func testUnpushedLocalRowBeatsARowTheServerHasStored() {
 52        let unpushedLocal = trackedDomainRow("example.com", isPinned: true, serverDate: nil, deviceDate: at(100))
 53        let remote = trackedDomainRow("example.com", isPinned: false, serverDate: at(99_999), deviceDate: at(99_999))
 54
 55        let merged = CloudSyncMerge.mergeTrackedDomains([unpushedLocal], [remote])
 56
 57        XCTAssertEqual(merged.domains.first?.value.isPinned, true)
 58    }
 59
 60    // MARK: Deletes
 61
 62    func testARowReAddedAfterItsDeletionSurvives() {
 63        let readded = trackedDomainRow("example.com", serverDate: at(200), deviceDate: at(200))
 64        let tombstone = tombstoneRow(.trackedDomain, "example.com", serverDate: at(100), deviceDate: at(100))
 65
 66        let surviving = CloudSyncMerge.applyTrackedDomainTombstones([readded], tombstones: [tombstone])
 67
 68        XCTAssertEqual(surviving.map(\.value.domain), ["example.com"])
 69    }
 70
 71    func testARowDeletedAfterItWasReAddedStaysDeleted() {
 72        let readded = trackedDomainRow("example.com", serverDate: at(100), deviceDate: at(100))
 73        let tombstone = tombstoneRow(.trackedDomain, "example.com", serverDate: at(200), deviceDate: at(200))
 74
 75        let surviving = CloudSyncMerge.applyTrackedDomainTombstones([readded], tombstones: [tombstone])
 76
 77        XCTAssertTrue(surviving.isEmpty)
 78    }
 79
 80    /// Both sides stamped in the same server instant. The tie goes to the
 81    /// tombstone: of the two mistakes available, resurrecting a row the user
 82    /// deleted is worse than dropping a re-add they can make again.
 83    func testATombstoneWinsATieWithTheRow() {
 84        let row = trackedDomainRow("example.com", serverDate: at(100), deviceDate: at(100))
 85        let tombstone = tombstoneRow(.trackedDomain, "example.com", serverDate: at(100), deviceDate: at(100))
 86
 87        XCTAssertTrue(CloudSyncMerge.applyTrackedDomainTombstones([row], tombstones: [tombstone]).isEmpty)
 88    }
 89
 90    /// A deletion recorded on this device and not yet pushed has no server
 91    /// date, so it outranks the copy of the row the server still holds —
 92    /// otherwise every sync would hand the deleted row straight back.
 93    func testAnUnpushedDeletionBeatsARowTheServerStillHolds() {
 94        let row = trackedDomainRow("example.com", serverDate: at(99_999), deviceDate: at(99_999))
 95        let tombstone = tombstoneRow(.trackedDomain, "example.com", serverDate: nil, deviceDate: at(100))
 96
 97        XCTAssertTrue(CloudSyncMerge.applyTrackedDomainTombstones([row], tombstones: [tombstone]).isEmpty)
 98    }
 99
100    func testWorkflowDeletesFollowTheSameRule() {
101        let identifier = UUID()
102        let workflow = workflowRow(identifier, serverDate: at(200), deviceDate: at(200))
103        let staleTombstone = tombstoneRow(.workflow, identifier.uuidString, serverDate: at(100), deviceDate: at(100))
104        let freshTombstone = tombstoneRow(.workflow, identifier.uuidString, serverDate: at(300), deviceDate: at(300))
105
106        XCTAssertEqual(CloudSyncMerge.applyWorkflowTombstones([workflow], tombstones: [staleTombstone]).count, 1)
107        XCTAssertTrue(CloudSyncMerge.applyWorkflowTombstones([workflow], tombstones: [freshTombstone]).isEmpty)
108    }
109
110    // MARK: The tombstone ledger
111
112    func testLatestTombstonesKeepsTheNewestPerIdentifier() {
113        let older = tombstoneRow(.trackedDomain, "example.com", serverDate: at(100), deviceDate: at(100))
114        let newer = tombstoneRow(.trackedDomain, "example.com", serverDate: at(200), deviceDate: at(200))
115
116        let latest = CloudSyncMerge.latestTombstones([newer, older])
117
118        XCTAssertEqual(latest.count, 1)
119        XCTAssertEqual(latest.first?.value.deletedAt, at(200))
120    }
121
122    func testLatestTombstonesKeepsOneEntryPerEntityType() {
123        let domain = tombstoneRow(.trackedDomain, "shared-identifier", serverDate: at(100), deviceDate: at(100))
124        let workflow = tombstoneRow(.workflow, "shared-identifier", serverDate: at(100), deviceDate: at(100))
125
126        XCTAssertEqual(CloudSyncMerge.latestTombstones([domain, workflow]).count, 2)
127    }
128
129    /// The cap drops the oldest deletions. Taking the first 200 encountered
130    /// instead would let a long ledger push out the deletions that still
131    /// matter and resurrect those rows.
132    func testTheLedgerCapKeepsTheNewestTombstones() {
133        let tombstones = (0..<250).map { index in
134            tombstoneRow(
135                .trackedDomain,
136                "domain-\(index).com",
137                serverDate: at(Double(index)),
138                deviceDate: at(Double(index))
139            )
140        }
141
142        let kept = CloudSyncMerge.newestTombstones(tombstones)
143
144        XCTAssertEqual(kept.count, CloudSyncMerge.tombstoneLedgerLimit)
145        XCTAssertEqual(kept.first?.value.identifier, "domain-249.com")
146        XCTAssertEqual(kept.last?.value.identifier, "domain-50.com")
147        XCTAssertFalse(kept.contains { $0.value.identifier == "domain-0.com" })
148    }
149
150    // MARK: Notes and history metadata
151
152    func testNotesFollowTheServerDate() {
153        let local = noteRow("example.com", text: "local", serverDate: at(200), deviceDate: at(100))
154        let skewedRemote = noteRow("example.com", text: "remote", serverDate: at(100), deviceDate: at(99_999))
155
156        let merged = CloudSyncMerge.mergeNotes(["example.com": local], ["example.com": skewedRemote])
157
158        XCTAssertEqual(merged.notesByDomain["example.com"]?.value.text, "local")
159        XCTAssertTrue(merged.hadConflict)
160    }
161
162    func testANoteOlderThanTheDeletionIsNotWrittenBackOntoTheRow() {
163        let row = trackedDomainRow("example.com", note: nil, serverDate: at(300), deviceDate: at(300))
164        let note = noteRow("example.com", text: "stale", serverDate: at(100), deviceDate: at(100))
165        let tombstone = tombstoneRow(.trackedDomain, "example.com", serverDate: at(200), deviceDate: at(200))
166
167        let updated = CloudSyncMerge.applyNotes(["example.com": note], to: [row], tombstones: [tombstone])
168
169        XCTAssertNil(updated.first?.value.note)
170    }
171
172    func testANoteNewerThanTheDeletionIsWrittenBackOntoTheRow() {
173        let row = trackedDomainRow("example.com", note: nil, serverDate: at(300), deviceDate: at(300))
174        let note = noteRow("example.com", text: "kept", serverDate: at(300), deviceDate: at(100))
175        let tombstone = tombstoneRow(.trackedDomain, "example.com", serverDate: at(200), deviceDate: at(200))
176
177        let updated = CloudSyncMerge.applyNotes(["example.com": note], to: [row], tombstones: [tombstone])
178
179        XCTAssertEqual(updated.first?.value.note, "kept")
180    }
181
182    func testHistoryMetadataFollowsTheServerDate() {
183        let local = historyMetadataRow("example.com", availability: .registered, serverDate: at(200), deviceDate: at(100))
184        let skewedRemote = historyMetadataRow("example.com", availability: .available, serverDate: at(100), deviceDate: at(99_999))
185
186        let merged = CloudSyncMerge.mergeHistoryMetadata(["example.com": local], ["example.com": skewedRemote])
187
188        XCTAssertEqual(merged.historyMetadataByDomain["example.com"]?.value.lastKnownAvailabilityRawValue, DomainAvailabilityStatus.registered.rawValue)
189    }
190
191    func testHistoryMetadataOlderThanTheDeletionIsNotApplied() {
192        let row = trackedDomainRow("example.com", serverDate: at(300), deviceDate: at(300))
193        let metadata = historyMetadataRow("example.com", availability: .available, serverDate: at(100), deviceDate: at(100))
194        let tombstone = tombstoneRow(.trackedDomain, "example.com", serverDate: at(200), deviceDate: at(200))
195
196        let updated = CloudSyncMerge.applyHistoryMetadata(["example.com": metadata], to: [row], tombstones: [tombstone])
197
198        XCTAssertNil(updated.first?.value.lastKnownAvailability)
199    }
200
201    // MARK: Tombstone retention
202
203    /// The window is what stops the zone growing without bound. A tombstone
204    /// older than it is deleted from the zone; everything newer stays, because
205    /// forgetting a deletion resurrects the row.
206    func testATombstoneOlderThanTheWindowExpires() {
207        let now = at(0)
208        let old = tombstoneRow(.trackedDomain, "old.example", serverDate: now.addingTimeInterval(-400 * 86_400), deviceDate: now.addingTimeInterval(-400 * 86_400))
209        let recent = tombstoneRow(.trackedDomain, "recent.example", serverDate: now.addingTimeInterval(-10 * 86_400), deviceDate: now.addingTimeInterval(-10 * 86_400))
210
211        let partitioned = CloudSyncMerge.partitionedTombstones([old, recent], now: now)
212
213        XCTAssertEqual(partitioned.kept.map(\.value.identifier), ["recent.example"])
214        XCTAssertEqual(partitioned.expired.map(\.value.identifier), ["old.example"])
215    }
216
217    /// A tombstone exactly on the boundary is kept. Of the two mistakes
218    /// available, resurrecting a row the user deleted is the worse one — the
219    /// same tie-break `applyTrackedDomainTombstones` makes.
220    func testATombstoneExactlyOnTheBoundaryIsKept() {
221        let now = at(0)
222        let boundary = tombstoneRow(
223            .trackedDomain,
224            "boundary.example",
225            serverDate: now.addingTimeInterval(-CloudSyncMerge.tombstoneRetention),
226            deviceDate: now.addingTimeInterval(-CloudSyncMerge.tombstoneRetention)
227        )
228
229        let partitioned = CloudSyncMerge.partitionedTombstones([boundary], now: now)
230
231        XCTAssertEqual(partitioned.kept.map(\.value.identifier), ["boundary.example"])
232        XCTAssertTrue(partitioned.expired.isEmpty)
233    }
234
235    /// Workflows carry tombstones too, and the window applies to the record
236    /// regardless of what it refers to.
237    func testTheWindowAppliesToWorkflowTombstones() {
238        let now = at(0)
239        let old = tombstoneRow(.workflow, "flow-1", serverDate: now.addingTimeInterval(-400 * 86_400), deviceDate: now.addingTimeInterval(-400 * 86_400))
240
241        XCTAssertEqual(
242            CloudSyncMerge.partitionedTombstones([old], now: now).expired.map(\.value.identifier),
243            ["flow-1"]
244        )
245    }
246
247    /// Nothing is dropped on a device that has only ever deleted rows
248    /// recently, which is the common case and must stay free of churn.
249    func testRecentDeletionsAreAllKept() {
250        let now = at(0)
251        let rows = (1...5).map { index in
252            tombstoneRow(
253                .trackedDomain,
254                "row-\(index).example",
255                serverDate: now.addingTimeInterval(-Double(index) * 86_400),
256                deviceDate: now.addingTimeInterval(-Double(index) * 86_400)
257            )
258        }
259
260        let partitioned = CloudSyncMerge.partitionedTombstones(rows, now: now)
261
262        XCTAssertEqual(partitioned.kept.count, 5)
263        XCTAssertTrue(partitioned.expired.isEmpty)
264    }
265
266    /// The deletion is still only on this device, so ageing it out would throw
267    /// away the deletion rather than a record of one — and the row would come
268    /// back from another device on the next sync.
269    func testADeletionTheServerHasNeverSeenNeverExpires() {
270        let now = at(0)
271        let unpushed = tombstoneRow(
272            .trackedDomain,
273            "offline.example",
274            serverDate: nil,
275            deviceDate: now.addingTimeInterval(-4_000 * 86_400)
276        )
277
278        let partitioned = CloudSyncMerge.partitionedTombstones([unpushed], now: now)
279
280        XCTAssertEqual(partitioned.kept.map(\.value.identifier), ["offline.example"])
281        XCTAssertTrue(partitioned.expired.isEmpty)
282    }
283
284    /// A year, stated as a test so a change to the constant is a deliberate
285    /// one rather than a silent shortening of everyone's safe offline window.
286    func testTheRetentionWindowIsAYear() {
287        XCTAssertEqual(CloudSyncMerge.tombstoneRetention, 365 * 24 * 60 * 60)
288    }
289
290    // MARK: Fixtures
291
292    private func at(_ offset: TimeInterval) -> Date {
293        Date(timeIntervalSinceReferenceDate: offset)
294    }
295
296    // MARK: Tags
297
298    /// `payloadTrackedDomain` rebuilds the row field by field, and every field
299    /// it forgets is written back to the local store by `applyMergedPayload`.
300    /// It used to forget `tags`, so one sync emptied every tracked domain's
301    /// tags and the watchlist's tag filter with them.
302    func testTagsSurviveThePayloadSanitizer() {
303        let trackedDomain = TrackedDomain(
304            domain: "example.com",
305            createdAt: at(0),
306            updatedAt: at(100),
307            tags: ["client-a", "production"]
308        )
309
310        let sanitized = CloudSyncMerge.payloadTrackedDomain(trackedDomain)
311
312        XCTAssertEqual(sanitized.tags, ["client-a", "production"])
313    }
314
315    func testTagsSurviveAMerge() {
316        let local = trackedDomainRow("example.com", tags: ["client-a"], serverDate: at(100), deviceDate: at(100))
317        let remote = trackedDomainRow("example.com", tags: ["client-b"], serverDate: at(200), deviceDate: at(200))
318
319        let merged = CloudSyncMerge.mergeTrackedDomains([local], [remote])
320
321        XCTAssertEqual(merged.domains.first?.value.tags, ["client-b"])
322    }
323
324    /// Records written before tags were carried decode with none at all, so an
325    /// empty list means "this side has nothing to say", not "cleared".
326    /// Otherwise the first sync after the fix would still drop them.
327    func testTagsFallBackWhenTheWinningSideHasNone() {
328        let local = trackedDomainRow("example.com", tags: ["client-a"], serverDate: at(100), deviceDate: at(100))
329        let legacyRemote = trackedDomainRow("example.com", tags: [], serverDate: at(200), deviceDate: at(200))
330
331        let merged = CloudSyncMerge.mergeTrackedDomains([local], [legacyRemote])
332
333        XCTAssertEqual(merged.domains.first?.value.tags, ["client-a"])
334    }
335
336    private func trackedDomainRow(
337        _ domain: String,
338        note: String? = nil,
339        isPinned: Bool = false,
340        tags: [String] = [],
341        serverDate: Date?,
342        deviceDate: Date
343    ) -> SyncRow<TrackedDomain> {
344        SyncRow(
345            value: TrackedDomain(
346                domain: domain,
347                createdAt: at(0),
348                updatedAt: deviceDate,
349                note: note,
350                isPinned: isPinned,
351                tags: tags
352            ),
353            orderKey: SyncOrderKey(serverDate: serverDate, deviceDate: deviceDate)
354        )
355    }
356
357    private func workflowRow(_ identifier: UUID, serverDate: Date?, deviceDate: Date) -> SyncRow<DomainWorkflow> {
358        SyncRow(
359            value: DomainWorkflow(
360                id: identifier,
361                name: "Workflow",
362                domains: ["example.com"],
363                createdAt: at(0),
364                updatedAt: deviceDate
365            ),
366            orderKey: SyncOrderKey(serverDate: serverDate, deviceDate: deviceDate)
367        )
368    }
369
370    private func tombstoneRow(
371        _ entityType: SyncEntityType,
372        _ identifier: String,
373        serverDate: Date?,
374        deviceDate: Date
375    ) -> SyncRow<SyncTombstone> {
376        SyncRow(
377            value: SyncTombstone(entityType: entityType, identifier: identifier, deletedAt: deviceDate),
378            orderKey: SyncOrderKey(serverDate: serverDate, deviceDate: deviceDate)
379        )
380    }
381
382    private func noteRow(_ domain: String, text: String, serverDate: Date?, deviceDate: Date) -> SyncRow<SyncedDomainNote> {
383        SyncRow(
384            value: SyncedDomainNote(domain: domain, text: text, updatedAt: deviceDate),
385            orderKey: SyncOrderKey(serverDate: serverDate, deviceDate: deviceDate)
386        )
387    }
388
389    private func historyMetadataRow(
390        _ domain: String,
391        availability: DomainAvailabilityStatus,
392        serverDate: Date?,
393        deviceDate: Date
394    ) -> SyncRow<SyncedHistoryMetadata> {
395        SyncRow(
396            value: SyncedHistoryMetadata(
397                domain: domain,
398                lastKnownAvailabilityRawValue: availability.rawValue,
399                lastChangeMessage: nil,
400                lastChangeSeverityRawValue: nil,
401                certificateWarningLevelRawValue: CertificateWarningLevel.none.rawValue,
402                certificateDaysRemaining: nil,
403                lastObservedAt: deviceDate,
404                updatedAt: deviceDate
405            ),
406            orderKey: SyncOrderKey(serverDate: serverDate, deviceDate: deviceDate)
407        )
408    }
409}