| @@ -80,52 +80,38 @@ private enum CloudRecordKey { |
| 80 | static let deletedAt = "deletedAt" |
80 | static let deletedAt = "deletedAt" |
| 81 | } |
81 | } |
| 82 | |
82 | |
| 83 | private enum SyncEntityType: String, Codable { |
83 | private struct SyncPayload { |
| 84 | case trackedDomain |
84 | var trackedDomains: [SyncRow<TrackedDomain>] |
| 85 | case workflow |
85 | var workflows: [SyncRow<DomainWorkflow>] |
| 86 | } |
86 | var appSettings: SyncRow<SyncedAppSettings> |
| 87 | |
87 | var monitoringSettings: SyncRow<SyncedMonitoringSettings> |
| 88 | private struct SyncedAppSettings: Codable { |
88 | var notesByDomain: [String: SyncRow<SyncedDomainNote>] |
| 89 | var snapshot: AppSettingsSnapshot |
89 | var historyMetadataByDomain: [String: SyncRow<SyncedHistoryMetadata>] |
| 90 | var updatedAt: Date |
90 | var tombstones: [SyncRow<SyncTombstone>] |
| 91 | } |
| |
| 92 | |
| |
| 93 | private struct SyncedMonitoringSettings: Codable { |
| |
| 94 | var settings: MonitoringSettings |
| |
| 95 | var updatedAt: Date |
| |
| 96 | } |
| |
| 97 | |
| |
| 98 | private struct SyncedDomainNote: Codable, Equatable { |
| |
| 99 | var domain: String |
| |
| 100 | var text: String |
| |
| 101 | var updatedAt: Date |
| |
| 102 | } |
91 | } |
| 103 | |
92 | |
| 104 | private struct SyncedHistoryMetadata: Codable, Equatable { |
93 | /// What a remote fetch produced: the payload, and the change token each zone |
| 105 | var domain: String |
94 | /// may resume from once the payload has been merged and pushed. |
| 106 | var lastKnownAvailabilityRawValue: String? |
95 | private struct RemoteSyncState { |
| 107 | var lastChangeMessage: String? |
96 | var payload: SyncPayload |
| 108 | var lastChangeSeverityRawValue: Int? |
97 | var changeTokens: [String: CKServerChangeToken] |
| 109 | var certificateWarningLevelRawValue: String |
| |
| 110 | var certificateDaysRemaining: Int? |
| |
| 111 | var lastObservedAt: Date? |
| |
| 112 | var updatedAt: Date |
| |
| 113 | } |
98 | } |
| 114 | |
99 | |
| 115 | private struct SyncTombstone: Codable, Equatable { |
100 | /// One pass of `CKFetchRecordZoneChangesOperation`: the zones that still have |
| 116 | var entityType: SyncEntityType |
101 | /// more coming, the token each zone reached, and the zones whose stored token |
| 117 | var identifier: String |
102 | /// the server has aged out. |
| 118 | var deletedAt: Date |
103 | private struct ZoneChangesStep { |
| |
104 | var pendingByZone: [CKRecordZone.ID: CKServerChangeToken?] |
| |
105 | var tokensByZone: [CKRecordZone.ID: CKServerChangeToken] |
| |
106 | var expiredZones: [CKRecordZone.ID] |
| 119 | } |
107 | } |
| 120 | |
108 | |
| 121 | private struct SyncPayload { |
109 | /// The server date this device last saw for a record, with the payload date the |
| 122 | var trackedDomains: [TrackedDomain] |
110 | /// row carried at that moment. A row whose payload date has moved since has a |
| 123 | var workflows: [DomainWorkflow] |
111 | /// local change the server has not seen. |
| 124 | var appSettings: SyncedAppSettings |
112 | private struct StoredRowAuthority: Codable { |
| 125 | var monitoringSettings: SyncedMonitoringSettings |
113 | var serverDate: Date |
| 126 | var notesByDomain: [String: SyncedDomainNote] |
114 | var deviceDate: Date |
| 127 | var historyMetadataByDomain: [String: SyncedHistoryMetadata] |
| |
| 128 | var tombstones: [SyncTombstone] |
| |
| 129 | } |
115 | } |
| 130 | |
116 | |
| 131 | private enum SyncDatabaseScope { |
117 | private enum SyncDatabaseScope { |
| @@ -175,6 +161,8 @@ final class CloudSyncService { |
| 175 | static let noteUpdatedAtByDomain = "cloudSync.noteUpdatedAtByDomain" |
161 | static let noteUpdatedAtByDomain = "cloudSync.noteUpdatedAtByDomain" |
| 176 | static let tombstones = "cloudSync.tombstones" |
162 | static let tombstones = "cloudSync.tombstones" |
| 177 | static let monitoringLocalActivationConfirmed = "cloudSync.monitoringLocalActivationConfirmed" |
163 | static let monitoringLocalActivationConfirmed = "cloudSync.monitoringLocalActivationConfirmed" |
| |
164 | static let rowAuthority = "cloudSync.rowAuthority" |
| |
165 | static let changeTokenPrefix = "cloudSync.changeToken." |
| 178 | } |
166 | } |
| 179 | |
167 | |
| 180 | private init(defaults: UserDefaults = .standard) { |
168 | private init(defaults: UserDefaults = .standard) { |
| @@ -283,7 +271,7 @@ final class CloudSyncService { |
| 283 | } |
271 | } |
| 284 | |
272 | |
| 285 | func markNoteChanged(for domain: String, updatedAt: Date = Date()) { |
273 | func markNoteChanged(for domain: String, updatedAt: Date = Date()) { |
| 286 | let normalized = Self.normalizeDomain(domain) |
274 | let normalized = CloudSyncMerge.normalizeDomain(domain) |
| 287 | guard !normalized.isEmpty else { return } |
275 | guard !normalized.isEmpty else { return } |
| 288 | |
276 | |
| 289 | var noteDates = loadNoteUpdatedAtByDomain() |
277 | var noteDates = loadNoteUpdatedAtByDomain() |
| @@ -293,7 +281,7 @@ final class CloudSyncService { |
| 293 | } |
281 | } |
| 294 | |
282 | |
| 295 | func recordTrackedDomainDeletion(_ trackedDomain: TrackedDomain, deletedAt: Date = Date()) { |
283 | func recordTrackedDomainDeletion(_ trackedDomain: TrackedDomain, deletedAt: Date = Date()) { |
| 296 | let normalized = Self.normalizeDomain(trackedDomain.domain) |
284 | let normalized = CloudSyncMerge.normalizeDomain(trackedDomain.domain) |
| 297 | guard !normalized.isEmpty else { return } |
285 | guard !normalized.isEmpty else { return } |
| 298 | saveTombstone(.init(entityType: .trackedDomain, identifier: normalized, deletedAt: deletedAt)) |
286 | saveTombstone(.init(entityType: .trackedDomain, identifier: normalized, deletedAt: deletedAt)) |
| 299 | |
287 | |
| @@ -363,9 +351,9 @@ final class CloudSyncService { |
| 363 | |
351 | |
| 364 | switch entity { |
352 | switch entity { |
| 365 | case .trackedDomain(let domain): |
353 | case .trackedDomain(let domain): |
| 366 | let normalized = Self.normalizeDomain(domain) |
354 | let normalized = CloudSyncMerge.normalizeDomain(domain) |
| 367 | let trackedDomain = DomainDataPortabilityService.loadTrackedDomains() |
355 | let trackedDomain = DomainDataPortabilityService.loadTrackedDomains() |
| 368 | .first(where: { Self.normalizeDomain($0.domain) == normalized }) |
356 | .first(where: { CloudSyncMerge.normalizeDomain($0.domain) == normalized }) |
| 369 | guard let trackedDomain else { |
357 | guard let trackedDomain else { |
| 370 | throw CloudSyncRuntimeError.missingLocalItem |
358 | throw CloudSyncRuntimeError.missingLocalItem |
| 371 | } |
359 | } |
| @@ -462,9 +450,20 @@ final class CloudSyncService { |
| 462 | do { |
450 | do { |
| 463 | let local = loadLocalPayload() |
451 | let local = loadLocalPayload() |
| 464 | let remote = try await fetchRemotePayload() |
452 | let remote = try await fetchRemotePayload() |
| 465 | let merged = merge(local: local, remote: remote) |
453 | let merged = merge(local: local, remote: remote.payload) |
| 466 | applyMergedPayload(merged.payload) |
454 | applyMergedPayload(merged.payload) |
| 467 | try await pushMergedPayload(merged.payload) |
455 | let pushedServerDates = try await pushMergedPayload(merged.payload) |
| |
456 | |
| |
457 | // Recorded from a reload rather than from the merged payload: the |
| |
458 | // local stores round-trip dates through ISO-8601 and through |
| |
459 | // `JSONEncoder`, and the next sync compares against what they read |
| |
460 | // back, not against the in-memory values. |
| |
461 | recordRowAuthority(in: loadLocalPayload(), remote: remote.payload, pushedServerDates: pushedServerDates) |
| |
462 | |
| |
463 | // Only once the fetched changes are on disk and the push went |
| |
464 | // through: a token committed earlier would skip those changes |
| |
465 | // forever if either step failed. |
| |
466 | commitChangeTokens(remote.changeTokens) |
| 468 | |
467 | |
| 469 | lastSyncDate = Date() |
468 | lastSyncDate = Date() |
| 470 | defaults.set(lastSyncDate, forKey: StorageKey.lastSyncDate) |
469 | defaults.set(lastSyncDate, forKey: StorageKey.lastSyncDate) |
| @@ -486,8 +485,10 @@ final class CloudSyncService { |
| 486 | } |
485 | } |
| 487 | |
486 | |
| 488 | private func loadLocalPayload() -> SyncPayload { |
487 | private func loadLocalPayload() -> SyncPayload { |
| |
488 | let authority = loadRowAuthority() |
| 489 | let trackedDomains = DomainDataPortabilityService.loadTrackedDomains() |
489 | let trackedDomains = DomainDataPortabilityService.loadTrackedDomains() |
| 490 | let workflows = DomainDataPortabilityService.loadWorkflows() |
490 | let workflows = DomainDataPortabilityService.loadWorkflows() |
| |
491 | |
| 491 | let appSettings = SyncedAppSettings( |
492 | let appSettings = SyncedAppSettings( |
| 492 | snapshot: DomainDataPortabilityService.loadAppSettings(), |
493 | snapshot: DomainDataPortabilityService.loadAppSettings(), |
| 493 | updatedAt: defaults.object(forKey: StorageKey.appSettingsUpdatedAt) as? Date ?? .distantPast |
494 | updatedAt: defaults.object(forKey: StorageKey.appSettingsUpdatedAt) as? Date ?? .distantPast |
| @@ -498,84 +499,164 @@ final class CloudSyncService { |
| 498 | ) |
499 | ) |
| 499 | |
500 | |
| 500 | let noteDates = loadNoteUpdatedAtByDomain() |
501 | let noteDates = loadNoteUpdatedAtByDomain() |
| 501 | let notesByDomain = Dictionary(uniqueKeysWithValues: trackedDomains.compactMap { trackedDomain -> (String, SyncedDomainNote)? in |
502 | var notesByDomain: [String: SyncRow<SyncedDomainNote>] = [:] |
| 502 | guard trackedDomain.collaboration?.scope != .sharedDatabase else { return nil } |
503 | var historyMetadataByDomain: [String: SyncRow<SyncedHistoryMetadata>] = [:] |
| 503 | let normalized = Self.normalizeDomain(trackedDomain.domain) |
504 | |
| 504 | guard !normalized.isEmpty else { return nil } |
505 | for trackedDomain in trackedDomains { |
| 505 | let noteText = trackedDomain.note ?? "" |
506 | guard trackedDomain.collaboration?.scope != .sharedDatabase else { continue } |
| 506 | let updatedAt = noteDates[normalized] ?? trackedDomain.updatedAt |
507 | let normalized = CloudSyncMerge.normalizeDomain(trackedDomain.domain) |
| 507 | return ( |
508 | guard !normalized.isEmpty else { continue } |
| 508 | normalized, |
509 | |
| 509 | SyncedDomainNote( |
510 | let note = SyncedDomainNote( |
| 510 | domain: normalized, |
511 | domain: normalized, |
| 511 | text: noteText, |
512 | text: trackedDomain.note ?? "", |
| 512 | updatedAt: updatedAt |
513 | updatedAt: noteDates[normalized] ?? trackedDomain.updatedAt |
| 513 | ) |
514 | ) |
| |
515 | notesByDomain[normalized] = SyncRow( |
| |
516 | value: note, |
| |
517 | orderKey: localOrderKey(authority, recordName: domainNoteRecordName(for: normalized), deviceDate: note.updatedAt) |
| 514 | ) |
518 | ) |
| 515 | }) |
| |
| 516 | |
519 | |
| 517 | let historyMetadataByDomain = Dictionary(uniqueKeysWithValues: trackedDomains.compactMap { trackedDomain -> (String, SyncedHistoryMetadata)? in |
520 | let metadata = SyncedHistoryMetadata( |
| 518 | guard trackedDomain.collaboration?.scope != .sharedDatabase else { return nil } |
521 | domain: normalized, |
| 519 | let normalized = Self.normalizeDomain(trackedDomain.domain) |
522 | lastKnownAvailabilityRawValue: trackedDomain.lastKnownAvailability?.rawValue, |
| 520 | guard !normalized.isEmpty else { return nil } |
523 | lastChangeMessage: trackedDomain.lastChangeSummary?.message, |
| 521 | return ( |
524 | lastChangeSeverityRawValue: trackedDomain.lastChangeSeverity?.rawValue ?? trackedDomain.lastChangeSummary?.severity.rawValue, |
| 522 | normalized, |
525 | certificateWarningLevelRawValue: trackedDomain.certificateWarningLevel.rawValue, |
| 523 | SyncedHistoryMetadata( |
526 | certificateDaysRemaining: trackedDomain.certificateDaysRemaining, |
| 524 | domain: normalized, |
527 | lastObservedAt: trackedDomain.updatedAt, |
| 525 | lastKnownAvailabilityRawValue: trackedDomain.lastKnownAvailability?.rawValue, |
528 | updatedAt: trackedDomain.updatedAt |
| 526 | lastChangeMessage: trackedDomain.lastChangeSummary?.message, |
| |
| 527 | lastChangeSeverityRawValue: trackedDomain.lastChangeSeverity?.rawValue ?? trackedDomain.lastChangeSummary?.severity.rawValue, |
| |
| 528 | certificateWarningLevelRawValue: trackedDomain.certificateWarningLevel.rawValue, |
| |
| 529 | certificateDaysRemaining: trackedDomain.certificateDaysRemaining, |
| |
| 530 | lastObservedAt: trackedDomain.updatedAt, |
| |
| 531 | updatedAt: trackedDomain.updatedAt |
| |
| 532 | ) |
| |
| 533 | ) |
529 | ) |
| 534 | }) |
530 | historyMetadataByDomain[normalized] = SyncRow( |
| |
531 | value: metadata, |
| |
532 | orderKey: localOrderKey(authority, recordName: historyMetadataRecordName(for: normalized), deviceDate: metadata.updatedAt) |
| |
533 | ) |
| |
534 | } |
| 535 | |
535 | |
| 536 | return SyncPayload( |
536 | return SyncPayload( |
| 537 | trackedDomains: trackedDomains, |
537 | trackedDomains: trackedDomains.map { trackedDomain in |
| 538 | workflows: workflows, |
538 | SyncRow( |
| 539 | appSettings: appSettings, |
539 | value: trackedDomain, |
| 540 | monitoringSettings: monitoringSettings, |
540 | orderKey: localOrderKey( |
| |
541 | authority, |
| |
542 | recordName: trackedDomainRecordName(for: CloudSyncMerge.normalizeDomain(trackedDomain.domain)), |
| |
543 | deviceDate: trackedDomain.updatedAt |
| |
544 | ) |
| |
545 | ) |
| |
546 | }, |
| |
547 | workflows: workflows.map { workflow in |
| |
548 | SyncRow( |
| |
549 | value: workflow, |
| |
550 | orderKey: localOrderKey( |
| |
551 | authority, |
| |
552 | recordName: workflowRecordName(for: workflow.id.uuidString), |
| |
553 | deviceDate: workflow.updatedAt |
| |
554 | ) |
| |
555 | ) |
| |
556 | }, |
| |
557 | appSettings: SyncRow( |
| |
558 | value: appSettings, |
| |
559 | orderKey: localOrderKey(authority, recordName: appSettingsRecordName, deviceDate: appSettings.updatedAt) |
| |
560 | ), |
| |
561 | monitoringSettings: SyncRow( |
| |
562 | value: monitoringSettings, |
| |
563 | orderKey: localOrderKey(authority, recordName: monitoringSettingsRecordName, deviceDate: monitoringSettings.updatedAt) |
| |
564 | ), |
| 541 | notesByDomain: notesByDomain, |
565 | notesByDomain: notesByDomain, |
| 542 | historyMetadataByDomain: historyMetadataByDomain, |
566 | historyMetadataByDomain: historyMetadataByDomain, |
| 543 | tombstones: loadTombstones() |
567 | tombstones: loadTombstones().map { tombstone in |
| |
568 | SyncRow( |
| |
569 | value: tombstone, |
| |
570 | orderKey: localOrderKey( |
| |
571 | authority, |
| |
572 | recordName: tombstoneRecordName(for: tombstone.entityType, identifier: tombstone.identifier), |
| |
573 | deviceDate: tombstone.deletedAt |
| |
574 | ) |
| |
575 | ) |
| |
576 | } |
| 544 | ) |
577 | ) |
| 545 | } |
578 | } |
| 546 | |
579 | |
| 547 | private func fetchRemotePayload() async throws -> SyncPayload { |
580 | private func fetchRemotePayload() async throws -> RemoteSyncState { |
| 548 | let privateRecords = try await fetchZoneRecords(in: .privateDatabase) |
581 | let privateFetch = try await fetchZoneRecords(in: .privateDatabase) |
| 549 | let sharedRecords = try await fetchZoneRecords(in: .sharedDatabase) |
582 | let sharedFetch = try await fetchZoneRecords(in: .sharedDatabase) |
| |
583 | let privateRecords = privateFetch.records |
| |
584 | let sharedRecords = sharedFetch.records |
| 550 | |
585 | |
| 551 | let privateTrackedDomains = try await trackedDomains(from: privateRecords, in: .privateDatabase) |
586 | let privateTrackedDomains = try await trackedDomains(from: privateRecords, in: .privateDatabase) |
| 552 | let sharedTrackedDomains = try await trackedDomains(from: sharedRecords, in: .sharedDatabase) |
587 | let sharedTrackedDomains = try await trackedDomains(from: sharedRecords, in: .sharedDatabase) |
| 553 | let privateWorkflows = try await workflows(from: privateRecords, in: .privateDatabase) |
588 | let privateWorkflows = try await workflows(from: privateRecords, in: .privateDatabase) |
| 554 | let sharedWorkflows = try await workflows(from: sharedRecords, in: .sharedDatabase) |
589 | let sharedWorkflows = try await workflows(from: sharedRecords, in: .sharedDatabase) |
| 555 | |
590 | |
| 556 | let appSettingsRecords: [SyncedAppSettings] = decodeRecords(privateRecords, ofType: CloudRecordType.appSettings) |
591 | let appSettingsRecords: [SyncRow<SyncedAppSettings>] = decodeRecords( |
| 557 | let monitoringSettingsRecords: [SyncedMonitoringSettings] = decodeRecords(privateRecords, ofType: CloudRecordType.monitoringSettings) |
592 | privateRecords, |
| 558 | let domainNotes: [SyncedDomainNote] = decodeRecords(privateRecords, ofType: CloudRecordType.domainNote) |
593 | ofType: CloudRecordType.appSettings, |
| 559 | let historyMetadata: [SyncedHistoryMetadata] = decodeRecords(privateRecords, ofType: CloudRecordType.historyMetadata) |
594 | deviceDate: \.updatedAt |
| 560 | let tombstones: [SyncTombstone] = decodeRecords(privateRecords, ofType: CloudRecordType.tombstone) |
595 | ) |
| |
596 | let monitoringSettingsRecords: [SyncRow<SyncedMonitoringSettings>] = decodeRecords( |
| |
597 | privateRecords, |
| |
598 | ofType: CloudRecordType.monitoringSettings, |
| |
599 | deviceDate: \.updatedAt |
| |
600 | ) |
| |
601 | let domainNotes: [SyncRow<SyncedDomainNote>] = decodeRecords( |
| |
602 | privateRecords, |
| |
603 | ofType: CloudRecordType.domainNote, |
| |
604 | deviceDate: \.updatedAt |
| |
605 | ) |
| |
606 | let historyMetadata: [SyncRow<SyncedHistoryMetadata>] = decodeRecords( |
| |
607 | privateRecords, |
| |
608 | ofType: CloudRecordType.historyMetadata, |
| |
609 | deviceDate: \.updatedAt |
| |
610 | ) |
| |
611 | let tombstones: [SyncRow<SyncTombstone>] = decodeRecords( |
| |
612 | privateRecords, |
| |
613 | ofType: CloudRecordType.tombstone, |
| |
614 | deviceDate: \.deletedAt |
| |
615 | ) |
| 561 | |
616 | |
| 562 | let appSettings = appSettingsRecords.max(by: { $0.updatedAt < $1.updatedAt }) |
617 | let appSettings = appSettingsRecords.max(by: { SyncOrderKey.isNewer($1.orderKey, $0.orderKey) }) |
| 563 | ?? SyncedAppSettings(snapshot: DomainDataPortabilityService.loadAppSettings(), updatedAt: .distantPast) |
618 | ?? SyncRow( |
| 564 | let monitoringSettings = monitoringSettingsRecords.max(by: { $0.updatedAt < $1.updatedAt }) |
619 | value: SyncedAppSettings(snapshot: DomainDataPortabilityService.loadAppSettings(), updatedAt: .distantPast), |
| 565 | ?? SyncedMonitoringSettings(settings: DomainDataPortabilityService.loadMonitoringSettings(), updatedAt: .distantPast) |
620 | orderKey: Self.absentRemoteOrderKey |
| |
621 | ) |
| |
622 | let monitoringSettings = monitoringSettingsRecords.max(by: { SyncOrderKey.isNewer($1.orderKey, $0.orderKey) }) |
| |
623 | ?? SyncRow( |
| |
624 | value: SyncedMonitoringSettings(settings: DomainDataPortabilityService.loadMonitoringSettings(), updatedAt: .distantPast), |
| |
625 | orderKey: Self.absentRemoteOrderKey |
| |
626 | ) |
| 566 | |
627 | |
| 567 | return SyncPayload( |
628 | let payload = SyncPayload( |
| 568 | trackedDomains: privateTrackedDomains + sharedTrackedDomains, |
629 | trackedDomains: privateTrackedDomains + sharedTrackedDomains, |
| 569 | workflows: privateWorkflows + sharedWorkflows, |
630 | workflows: privateWorkflows + sharedWorkflows, |
| 570 | appSettings: appSettings, |
631 | appSettings: appSettings, |
| 571 | monitoringSettings: monitoringSettings, |
632 | monitoringSettings: monitoringSettings, |
| 572 | notesByDomain: Dictionary(uniqueKeysWithValues: domainNotes.map { (Self.normalizeDomain($0.domain), $0) }), |
633 | notesByDomain: Dictionary( |
| 573 | historyMetadataByDomain: Dictionary(uniqueKeysWithValues: historyMetadata.map { (Self.normalizeDomain($0.domain), $0) }), |
634 | domainNotes.map { (CloudSyncMerge.normalizeDomain($0.value.domain), $0) }, |
| |
635 | uniquingKeysWith: { SyncOrderKey.isAtLeastAsRecent($0.orderKey, $1.orderKey) ? $0 : $1 } |
| |
636 | ), |
| |
637 | historyMetadataByDomain: Dictionary( |
| |
638 | historyMetadata.map { (CloudSyncMerge.normalizeDomain($0.value.domain), $0) }, |
| |
639 | uniquingKeysWith: { SyncOrderKey.isAtLeastAsRecent($0.orderKey, $1.orderKey) ? $0 : $1 } |
| |
640 | ), |
| 574 | tombstones: tombstones |
641 | tombstones: tombstones |
| 575 | ) |
642 | ) |
| |
643 | |
| |
644 | return RemoteSyncState( |
| |
645 | payload: payload, |
| |
646 | changeTokens: privateFetch.changeTokens.merging(sharedFetch.changeTokens) { _, shared in shared } |
| |
647 | ) |
| 576 | } |
648 | } |
| 577 | |
649 | |
| 578 | private func pushMergedPayload(_ payload: SyncPayload) async throws { |
650 | /// Stands in for a singleton record the zone does not hold yet. It has to |
| |
651 | /// lose to anything real, so it carries the oldest possible server date |
| |
652 | /// rather than none — no server date means an unpushed local change, which |
| |
653 | /// wins. |
| |
654 | private static let absentRemoteOrderKey = SyncOrderKey(serverDate: .distantPast, deviceDate: .distantPast) |
| |
655 | |
| |
656 | /// Returns the server-assigned modification date of every record the push |
| |
657 | /// saved, keyed by record name. Those dates are what the next sync orders |
| |
658 | /// its conflicts by. |
| |
659 | private func pushMergedPayload(_ payload: SyncPayload) async throws -> [String: Date] { |
| 579 | guard let privateDatabase = cloudKitDatabase(in: .privateDatabase) else { |
660 | guard let privateDatabase = cloudKitDatabase(in: .privateDatabase) else { |
| 580 | throw CloudSyncRuntimeError.missingEntitlement |
661 | throw CloudSyncRuntimeError.missingEntitlement |
| 581 | } |
662 | } |
| @@ -586,7 +667,7 @@ final class CloudSyncService { |
| 586 | var sharedRecordsToSave: [CKRecord] = [] |
667 | var sharedRecordsToSave: [CKRecord] = [] |
| 587 | var recordIDsToDelete: [CKRecord.ID] = [] |
668 | var recordIDsToDelete: [CKRecord.ID] = [] |
| 588 | |
669 | |
| 589 | for trackedDomain in payload.trackedDomains { |
670 | for trackedDomain in payload.trackedDomains.map(\.value) { |
| 590 | switch trackedDomain.collaboration?.scope ?? .privateDatabase { |
671 | switch trackedDomain.collaboration?.scope ?? .privateDatabase { |
| 591 | case .privateDatabase: |
672 | case .privateDatabase: |
| 592 | privateRecordsToSave.append(makeTrackedDomainRecord(trackedDomain)) |
673 | privateRecordsToSave.append(makeTrackedDomainRecord(trackedDomain)) |
| @@ -597,7 +678,7 @@ final class CloudSyncService { |
| 597 | } |
678 | } |
| 598 | } |
679 | } |
| 599 | |
680 | |
| 600 | for workflow in payload.workflows { |
681 | for workflow in payload.workflows.map(\.value) { |
| 601 | switch workflow.collaboration?.scope ?? .privateDatabase { |
682 | switch workflow.collaboration?.scope ?? .privateDatabase { |
| 602 | case .privateDatabase: |
683 | case .privateDatabase: |
| 603 | privateRecordsToSave.append(makeWorkflowRecord(workflow)) |
684 | privateRecordsToSave.append(makeWorkflowRecord(workflow)) |
| @@ -608,13 +689,13 @@ final class CloudSyncService { |
| 608 | } |
689 | } |
| 609 | } |
690 | } |
| 610 | |
691 | |
| 611 | privateRecordsToSave.append(makeAppSettingsRecord(payload.appSettings)) |
692 | privateRecordsToSave.append(makeAppSettingsRecord(payload.appSettings.value)) |
| 612 | privateRecordsToSave.append(makeMonitoringSettingsRecord(payload.monitoringSettings)) |
693 | privateRecordsToSave.append(makeMonitoringSettingsRecord(payload.monitoringSettings.value)) |
| 613 | privateRecordsToSave.append(contentsOf: payload.notesByDomain.values.map(makeDomainNoteRecord)) |
694 | privateRecordsToSave.append(contentsOf: payload.notesByDomain.values.map { makeDomainNoteRecord($0.value) }) |
| 614 | privateRecordsToSave.append(contentsOf: payload.historyMetadataByDomain.values.map(makeHistoryMetadataRecord)) |
695 | privateRecordsToSave.append(contentsOf: payload.historyMetadataByDomain.values.map { makeHistoryMetadataRecord($0.value) }) |
| 615 | privateRecordsToSave.append(contentsOf: payload.tombstones.map(makeTombstoneRecord)) |
696 | privateRecordsToSave.append(contentsOf: payload.tombstones.map { makeTombstoneRecord($0.value) }) |
| 616 | |
697 | |
| 617 | for tombstone in payload.tombstones { |
698 | for tombstone in payload.tombstones.map(\.value) { |
| 618 | switch tombstone.entityType { |
699 | switch tombstone.entityType { |
| 619 | case .trackedDomain: |
700 | case .trackedDomain: |
| 620 | let identifier = tombstone.identifier |
701 | let identifier = tombstone.identifier |
| @@ -626,76 +707,97 @@ final class CloudSyncService { |
| 626 | } |
707 | } |
| 627 | } |
708 | } |
| 628 | |
709 | |
| 629 | _ = try await privateDatabase.modifyRecords( |
710 | let privateResults = try await privateDatabase.modifyRecords( |
| 630 | saving: privateRecordsToSave, |
711 | saving: privateRecordsToSave, |
| 631 | deleting: Array(Set(recordIDsToDelete)), |
712 | deleting: Array(Set(recordIDsToDelete)), |
| 632 | savePolicy: .changedKeys, |
713 | savePolicy: .changedKeys, |
| 633 | atomically: false |
714 | atomically: false |
| 634 | ) |
715 | ) |
| |
716 | var serverDates = Self.serverDates(from: privateResults.saveResults) |
| 635 | |
717 | |
| 636 | if !sharedRecordsToSave.isEmpty, let sharedDatabase = cloudKitDatabase(in: .sharedDatabase) { |
718 | if !sharedRecordsToSave.isEmpty, let sharedDatabase = cloudKitDatabase(in: .sharedDatabase) { |
| 637 | _ = try await sharedDatabase.modifyRecords( |
719 | let sharedResults = try await sharedDatabase.modifyRecords( |
| 638 | saving: sharedRecordsToSave, |
720 | saving: sharedRecordsToSave, |
| 639 | deleting: [], |
721 | deleting: [], |
| 640 | savePolicy: .changedKeys, |
722 | savePolicy: .changedKeys, |
| 641 | atomically: false |
723 | atomically: false |
| 642 | ) |
724 | ) |
| |
725 | serverDates.merge(Self.serverDates(from: sharedResults.saveResults)) { _, shared in shared } |
| |
726 | } |
| |
727 | |
| |
728 | return serverDates |
| |
729 | } |
| |
730 | |
| |
731 | private static func serverDates(from results: [CKRecord.ID: Result<CKRecord, Error>]) -> [String: Date] { |
| |
732 | results.reduce(into: [String: Date]()) { partialResult, entry in |
| |
733 | guard case .success(let record) = entry.value, let modificationDate = record.modificationDate else { return } |
| |
734 | partialResult[entry.key.recordName] = modificationDate |
| 643 | } |
735 | } |
| 644 | } |
736 | } |
| 645 | |
737 | |
| 646 | private func applyMergedPayload(_ payload: SyncPayload) { |
738 | private func applyMergedPayload(_ payload: SyncPayload) { |
| 647 | DomainDataPortabilityService.saveTrackedDomains(payload.trackedDomains) |
739 | DomainDataPortabilityService.saveTrackedDomains(payload.trackedDomains.map(\.value)) |
| 648 | DomainDataPortabilityService.saveWorkflows(payload.workflows) |
740 | DomainDataPortabilityService.saveWorkflows(payload.workflows.map(\.value)) |
| 649 | DomainDataPortabilityService.saveAppSettings(payload.appSettings.snapshot) |
741 | DomainDataPortabilityService.saveAppSettings(payload.appSettings.value.snapshot) |
| 650 | DomainDataPortabilityService.saveMonitoringSettings(payload.monitoringSettings.settings) |
742 | DomainDataPortabilityService.saveMonitoringSettings(payload.monitoringSettings.value.settings) |
| 651 | |
743 | |
| 652 | defaults.set(payload.appSettings.updatedAt, forKey: StorageKey.appSettingsUpdatedAt) |
744 | defaults.set(payload.appSettings.value.updatedAt, forKey: StorageKey.appSettingsUpdatedAt) |
| 653 | defaults.set(payload.monitoringSettings.updatedAt, forKey: StorageKey.monitoringSettingsUpdatedAt) |
745 | defaults.set(payload.monitoringSettings.value.updatedAt, forKey: StorageKey.monitoringSettingsUpdatedAt) |
| 654 | saveNoteUpdatedAtByDomain(Dictionary(uniqueKeysWithValues: payload.notesByDomain.map { ($0.key, $0.value.updatedAt) })) |
746 | saveNoteUpdatedAtByDomain(Dictionary(uniqueKeysWithValues: payload.notesByDomain.map { ($0.key, $0.value.value.updatedAt) })) |
| 655 | saveTombstones(payload.tombstones) |
747 | saveTombstones(payload.tombstones) |
| 656 | } |
748 | } |
| 657 | |
749 | |
| 658 | private func merge(local: SyncPayload, remote: SyncPayload) -> MergedSyncPayload { |
750 | private func merge(local: SyncPayload, remote: SyncPayload) -> MergedSyncPayload { |
| 659 | var hadConflict = false |
751 | var hadConflict = false |
| 660 | |
752 | |
| 661 | let tombstones = latestTombstones(local.tombstones + remote.tombstones) |
753 | let tombstones = CloudSyncMerge.latestTombstones(local.tombstones + remote.tombstones) |
| 662 | |
754 | |
| 663 | let trackedDomainsResult = mergeTrackedDomains(local.trackedDomains, remote.trackedDomains) |
755 | let trackedDomainsResult = CloudSyncMerge.mergeTrackedDomains(local.trackedDomains, remote.trackedDomains) |
| 664 | hadConflict = hadConflict || trackedDomainsResult.hadConflict |
756 | hadConflict = hadConflict || trackedDomainsResult.hadConflict |
| 665 | var trackedDomains = applyTrackedDomainTombstones(trackedDomainsResult.domains, tombstones: tombstones) |
757 | var trackedDomains = CloudSyncMerge.applyTrackedDomainTombstones(trackedDomainsResult.domains, tombstones: tombstones) |
| 666 | |
758 | |
| 667 | let workflowsResult = mergeWorkflows(local.workflows, remote.workflows) |
759 | let workflowsResult = CloudSyncMerge.mergeWorkflows(local.workflows, remote.workflows) |
| 668 | hadConflict = hadConflict || workflowsResult.hadConflict |
760 | hadConflict = hadConflict || workflowsResult.hadConflict |
| 669 | let workflows = applyWorkflowTombstones(workflowsResult.workflows, tombstones: tombstones) |
761 | let workflows = CloudSyncMerge.applyWorkflowTombstones(workflowsResult.workflows, tombstones: tombstones) |
| 670 | |
762 | |
| 671 | let notesResult = mergeNotes(local.notesByDomain, remote.notesByDomain) |
763 | let notesResult = CloudSyncMerge.mergeNotes(local.notesByDomain, remote.notesByDomain) |
| 672 | hadConflict = hadConflict || notesResult.hadConflict |
764 | hadConflict = hadConflict || notesResult.hadConflict |
| 673 | trackedDomains = applyNotes(notesResult.notesByDomain, to: trackedDomains, tombstones: tombstones) |
765 | trackedDomains = CloudSyncMerge.applyNotes(notesResult.notesByDomain, to: trackedDomains, tombstones: tombstones) |
| 674 | |
766 | |
| 675 | let historyResult = mergeHistoryMetadata(local.historyMetadataByDomain, remote.historyMetadataByDomain) |
767 | let historyResult = CloudSyncMerge.mergeHistoryMetadata(local.historyMetadataByDomain, remote.historyMetadataByDomain) |
| 676 | hadConflict = hadConflict || historyResult.hadConflict |
768 | hadConflict = hadConflict || historyResult.hadConflict |
| 677 | trackedDomains = applyHistoryMetadata(historyResult.historyMetadataByDomain, to: trackedDomains, tombstones: tombstones) |
769 | trackedDomains = CloudSyncMerge.applyHistoryMetadata(historyResult.historyMetadataByDomain, to: trackedDomains, tombstones: tombstones) |
| 678 | |
770 | |
| 679 | let appSettingsResult = mergeAppSettings(local.appSettings, remote.appSettings) |
771 | let appSettingsResult = CloudSyncMerge.mergeAppSettings(local.appSettings, remote.appSettings) |
| 680 | hadConflict = hadConflict || appSettingsResult.hadConflict |
772 | hadConflict = hadConflict || appSettingsResult.hadConflict |
| 681 | |
773 | |
| 682 | let monitoringResult = mergeMonitoringSettings(local.monitoringSettings, remote.monitoringSettings) |
774 | let monitoringResult = CloudSyncMerge.mergeMonitoringSettings( |
| |
775 | local.monitoringSettings, |
| |
776 | remote.monitoringSettings, |
| |
777 | localActivationConfirmed: defaults.bool(forKey: StorageKey.monitoringLocalActivationConfirmed) |
| |
778 | ) |
| 683 | hadConflict = hadConflict || monitoringResult.hadConflict |
779 | hadConflict = hadConflict || monitoringResult.hadConflict |
| 684 | |
780 | |
| 685 | let mergedPayload = SyncPayload( |
781 | let mergedPayload = SyncPayload( |
| 686 | trackedDomains: trackedDomains, |
782 | trackedDomains: trackedDomains, |
| 687 | workflows: workflows, |
783 | workflows: workflows, |
| 688 | appSettings: appSettingsResult.settings, |
784 | appSettings: SyncRow( |
| 689 | monitoringSettings: monitoringResult.settings, |
785 | value: appSettingsResult.settings, |
| 690 | notesByDomain: Dictionary(uniqueKeysWithValues: trackedDomains.compactMap { trackedDomain -> (String, SyncedDomainNote)? in |
786 | orderKey: CloudSyncMerge.mergedOrderKey(local.appSettings.orderKey, remote.appSettings.orderKey) |
| 691 | guard trackedDomain.collaboration?.scope != .sharedDatabase else { return nil } |
787 | ), |
| 692 | let normalized = Self.normalizeDomain(trackedDomain.domain) |
788 | monitoringSettings: SyncRow( |
| |
789 | value: monitoringResult.settings, |
| |
790 | orderKey: CloudSyncMerge.mergedOrderKey(local.monitoringSettings.orderKey, remote.monitoringSettings.orderKey) |
| |
791 | ), |
| |
792 | notesByDomain: Dictionary(uniqueKeysWithValues: trackedDomains.compactMap { row -> (String, SyncRow<SyncedDomainNote>)? in |
| |
793 | guard row.value.collaboration?.scope != .sharedDatabase else { return nil } |
| |
794 | let normalized = CloudSyncMerge.normalizeDomain(row.value.domain) |
| 693 | guard let note = notesResult.notesByDomain[normalized] else { return nil } |
795 | guard let note = notesResult.notesByDomain[normalized] else { return nil } |
| 694 | return (normalized, note) |
796 | return (normalized, note) |
| 695 | }), |
797 | }), |
| 696 | historyMetadataByDomain: Dictionary(uniqueKeysWithValues: trackedDomains.compactMap { trackedDomain -> (String, SyncedHistoryMetadata)? in |
798 | historyMetadataByDomain: Dictionary(uniqueKeysWithValues: trackedDomains.compactMap { row -> (String, SyncRow<SyncedHistoryMetadata>)? in |
| 697 | guard trackedDomain.collaboration?.scope != .sharedDatabase else { return nil } |
799 | guard row.value.collaboration?.scope != .sharedDatabase else { return nil } |
| 698 | let normalized = Self.normalizeDomain(trackedDomain.domain) |
800 | let normalized = CloudSyncMerge.normalizeDomain(row.value.domain) |
| 699 | guard let metadata = historyResult.historyMetadataByDomain[normalized] else { return nil } |
801 | guard let metadata = historyResult.historyMetadataByDomain[normalized] else { return nil } |
| 700 | return (normalized, metadata) |
802 | return (normalized, metadata) |
| 701 | }), |
803 | }), |
| @@ -703,10 +805,10 @@ final class CloudSyncService { |
| 703 | ) |
805 | ) |
| 704 | |
806 | |
| 705 | let changedLocalData = |
807 | let changedLocalData = |
| 706 | mergedPayload.trackedDomains != local.trackedDomains |
808 | mergedPayload.trackedDomains.map(\.value) != local.trackedDomains.map(\.value) |
| 707 | || mergedPayload.workflows != local.workflows |
809 | || mergedPayload.workflows.map(\.value) != local.workflows.map(\.value) |
| 708 | || !sameAppSettings(mergedPayload.appSettings.snapshot, local.appSettings.snapshot) |
810 | || !CloudSyncMerge.sameAppSettings(mergedPayload.appSettings.value.snapshot, local.appSettings.value.snapshot) |
| 709 | || mergedPayload.monitoringSettings.settings != local.monitoringSettings.settings |
811 | || mergedPayload.monitoringSettings.value.settings != local.monitoringSettings.value.settings |
| 710 | |
812 | |
| 711 | return MergedSyncPayload( |
813 | return MergedSyncPayload( |
| 712 | payload: mergedPayload, |
814 | payload: mergedPayload, |
| @@ -715,264 +817,127 @@ final class CloudSyncService { |
| 715 | ) |
817 | ) |
| 716 | } |
818 | } |
| 717 | |
819 | |
| 718 | private func mergeTrackedDomains(_ lhs: [TrackedDomain], _ rhs: [TrackedDomain]) -> (domains: [TrackedDomain], hadConflict: Bool) { |
820 | private func saveTombstone(_ tombstone: SyncTombstone) { |
| 719 | var mergedByDomain = Dictionary(uniqueKeysWithValues: lhs.map { (Self.normalizeDomain($0.domain), Self.payloadTrackedDomain($0)) }) |
821 | let authority = loadRowAuthority() |
| 720 | var hadConflict = false |
822 | var tombstones = loadTombstones().map { stored in |
| 721 | |
823 | SyncRow( |
| 722 | for trackedDomain in rhs.map(Self.payloadTrackedDomain) { |
824 | value: stored, |
| 723 | let key = Self.normalizeDomain(trackedDomain.domain) |
825 | orderKey: localOrderKey( |
| 724 | guard !key.isEmpty else { continue } |
826 | authority, |
| 725 | |
827 | recordName: tombstoneRecordName(for: stored.entityType, identifier: stored.identifier), |
| 726 | if let existing = mergedByDomain[key] { |
828 | deviceDate: stored.deletedAt |
| 727 | if existing != trackedDomain { |
| |
| 728 | hadConflict = true |
| |
| 729 | } |
| |
| 730 | mergedByDomain[key] = mergedTrackedDomain(existing, trackedDomain) |
| |
| 731 | } else { |
| |
| 732 | mergedByDomain[key] = trackedDomain |
| |
| 733 | } |
| |
| 734 | } |
| |
| 735 | |
| |
| 736 | let domains = mergedByDomain.values.sorted { |
| |
| 737 | if $0.updatedAt != $1.updatedAt { |
| |
| 738 | return $0.updatedAt > $1.updatedAt |
| |
| 739 | } |
| |
| 740 | return $0.domain.localizedCaseInsensitiveCompare($1.domain) == .orderedAscending |
| |
| 741 | } |
| |
| 742 | |
| |
| 743 | return (domains, hadConflict) |
| |
| 744 | } |
| |
| 745 | |
| |
| 746 | private func mergeWorkflows(_ lhs: [DomainWorkflow], _ rhs: [DomainWorkflow]) -> (workflows: [DomainWorkflow], hadConflict: Bool) { |
| |
| 747 | var merged = Dictionary(uniqueKeysWithValues: lhs.map { ($0.id, normalizedWorkflow($0)) }) |
| |
| 748 | var hadConflict = false |
| |
| 749 | |
| |
| 750 | for workflow in rhs.map(normalizedWorkflow) { |
| |
| 751 | if let existing = merged[workflow.id] { |
| |
| 752 | if existing != workflow { |
| |
| 753 | hadConflict = true |
| |
| 754 | } |
| |
| 755 | let winner = preferredWorkflow(existing, workflow) |
| |
| 756 | merged[workflow.id] = DomainWorkflow( |
| |
| 757 | id: existing.id, |
| |
| 758 | name: winner.name, |
| |
| 759 | domains: deduplicated(existing.domains + workflow.domains), |
| |
| 760 | createdAt: min(existing.createdAt, workflow.createdAt), |
| |
| 761 | updatedAt: max(existing.updatedAt, workflow.updatedAt), |
| |
| 762 | notes: winner.notes ?? existing.notes ?? workflow.notes, |
| |
| 763 | collaboration: preferredCollaboration(existing.collaboration, workflow.collaboration) |
| |
| 764 | ) |
829 | ) |
| 765 | } else { |
830 | ) |
| 766 | merged[workflow.id] = workflow |
| |
| 767 | } |
| |
| 768 | } |
831 | } |
| 769 | |
832 | // A deletion recorded right now has not been pushed, so it carries no |
| 770 | return ( |
833 | // server date and outranks whatever the server already holds. |
| 771 | merged.values.sorted { |
834 | tombstones.append(SyncRow(value: tombstone, orderKey: SyncOrderKey(serverDate: nil, deviceDate: tombstone.deletedAt))) |
| 772 | if $0.updatedAt != $1.updatedAt { |
835 | saveTombstones(tombstones) |
| 773 | return $0.updatedAt > $1.updatedAt |
| |
| 774 | } |
| |
| 775 | return $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending |
| |
| 776 | }, |
| |
| 777 | hadConflict |
| |
| 778 | ) |
| |
| 779 | } |
836 | } |
| 780 | |
837 | |
| 781 | private func mergeNotes( |
838 | private func loadTombstones() -> [SyncTombstone] { |
| 782 | _ lhs: [String: SyncedDomainNote], |
839 | guard let data = defaults.data(forKey: StorageKey.tombstones), |
| 783 | _ rhs: [String: SyncedDomainNote] |
840 | let tombstones = try? decoder.decode([SyncTombstone].self, from: data) else { |
| 784 | ) -> (notesByDomain: [String: SyncedDomainNote], hadConflict: Bool) { |
841 | return [] |
| 785 | let result = mergeLatest(lhs, rhs, updatedAt: \.updatedAt) |
842 | } |
| 786 | return (result.merged, result.hadConflict) |
843 | return tombstones |
| 787 | } |
844 | } |
| 788 | |
845 | |
| 789 | private func mergeHistoryMetadata( |
846 | private func saveTombstones(_ tombstones: [SyncRow<SyncTombstone>]) { |
| 790 | _ lhs: [String: SyncedHistoryMetadata], |
847 | if let data = try? encoder.encode(CloudSyncMerge.newestTombstones(tombstones).map(\.value)) { |
| 791 | _ rhs: [String: SyncedHistoryMetadata] |
848 | defaults.set(data, forKey: StorageKey.tombstones) |
| 792 | ) -> (historyMetadataByDomain: [String: SyncedHistoryMetadata], hadConflict: Bool) { |
849 | } |
| 793 | let result = mergeLatest(lhs, rhs, updatedAt: \.updatedAt) |
| |
| 794 | return (result.merged, result.hadConflict) |
| |
| 795 | } |
850 | } |
| 796 | |
851 | |
| 797 | /// `rhs` merged over `lhs` by domain; where both differ, the newer wins |
852 | private func loadRowAuthority() -> [String: StoredRowAuthority] { |
| 798 | /// (the local one on a tie) and the merge reports a conflict. |
853 | guard let data = defaults.data(forKey: StorageKey.rowAuthority), |
| 799 | private func mergeLatest<Value: Equatable>( |
854 | let values = try? decoder.decode([String: StoredRowAuthority].self, from: data) else { |
| 800 | _ lhs: [String: Value], |
855 | return [:] |
| 801 | _ rhs: [String: Value], |
| |
| 802 | updatedAt: KeyPath<Value, Date> |
| |
| 803 | ) -> (merged: [String: Value], hadConflict: Bool) { |
| |
| 804 | var merged = lhs |
| |
| 805 | var hadConflict = false |
| |
| 806 | |
| |
| 807 | for (domain, remote) in rhs { |
| |
| 808 | if let local = merged[domain], local != remote { |
| |
| 809 | hadConflict = true |
| |
| 810 | merged[domain] = local[keyPath: updatedAt] >= remote[keyPath: updatedAt] ? local : remote |
| |
| 811 | } else { |
| |
| 812 | merged[domain] = remote |
| |
| 813 | } |
| |
| 814 | } |
856 | } |
| 815 | |
857 | return values |
| 816 | return (merged, hadConflict) |
| |
| 817 | } |
858 | } |
| 818 | |
859 | |
| 819 | private func mergeAppSettings(_ lhs: SyncedAppSettings, _ rhs: SyncedAppSettings) -> (settings: SyncedAppSettings, hadConflict: Bool) { |
860 | /// The order key for a row read out of the local store. |
| 820 | let winner = lhs.updatedAt >= rhs.updatedAt ? lhs : rhs |
861 | /// |
| 821 | let loser = winner.updatedAt == lhs.updatedAt ? rhs : lhs |
862 | /// A row keeps the server date this device last saw for it, but only while |
| 822 | |
863 | /// its payload date still matches the one recorded then. Any later local |
| 823 | let merged = SyncedAppSettings( |
864 | /// edit moves that date, which marks the row as a change the server has |
| 824 | snapshot: AppSettingsSnapshot( |
865 | /// never seen. Both dates in that comparison were minted by this one |
| 825 | recentSearches: deduplicated(winner.snapshot.recentSearches + loser.snapshot.recentSearches).prefix(20).map { $0 }, |
866 | /// device, so no other device's clock enters into it. |
| 826 | savedDomains: deduplicated(winner.snapshot.savedDomains + loser.snapshot.savedDomains), |
867 | private func localOrderKey( |
| 827 | resolverURLString: winner.snapshot.resolverURLString, |
868 | _ authority: [String: StoredRowAuthority], |
| 828 | appDensityRawValue: winner.snapshot.appDensityRawValue |
869 | recordName: String, |
| 829 | ), |
870 | deviceDate: Date |
| 830 | updatedAt: max(lhs.updatedAt, rhs.updatedAt) |
871 | ) -> SyncOrderKey { |
| |
872 | guard let stored = authority[recordName], stored.deviceDate == deviceDate else { |
| |
873 | return SyncOrderKey(serverDate: nil, deviceDate: deviceDate) |
| |
874 | } |
| |
875 | return SyncOrderKey(serverDate: stored.serverDate, deviceDate: deviceDate) |
| |
876 | } |
| |
877 | |
| |
878 | /// Remembers the server date behind every row the sync just settled. Rows |
| |
879 | /// that are no longer in the payload are dropped, so the map stays the size |
| |
880 | /// of the data rather than of everything ever seen. |
| |
881 | /// |
| |
882 | /// The first sync after this bookkeeping arrives has no recorded dates at |
| |
883 | /// all, so every local row counts as unpushed and wins that one merge. |
| |
884 | private func recordRowAuthority(in payload: SyncPayload, remote: SyncPayload, pushedServerDates: [String: Date]) { |
| |
885 | let remoteServerDates = Dictionary( |
| |
886 | rowDates(in: remote).compactMap { entry in entry.serverDate.map { (entry.recordName, $0) } }, |
| |
887 | uniquingKeysWith: { max($0, $1) } |
| 831 | ) |
888 | ) |
| 832 | |
889 | |
| 833 | return (merged, !sameAppSettings(lhs.snapshot, rhs.snapshot) || lhs.updatedAt != rhs.updatedAt) |
890 | let previous = loadRowAuthority() |
| 834 | } |
891 | var authority: [String: StoredRowAuthority] = [:] |
| 835 | |
892 | for entry in rowDates(in: payload) { |
| 836 | private func mergeMonitoringSettings( |
893 | if let serverDate = pushedServerDates[entry.recordName] ?? remoteServerDates[entry.recordName] { |
| 837 | _ lhs: SyncedMonitoringSettings, |
894 | authority[entry.recordName] = StoredRowAuthority(serverDate: serverDate, deviceDate: entry.deviceDate) |
| 838 | _ rhs: SyncedMonitoringSettings |
895 | } else if let carried = previous[entry.recordName], carried.deviceDate == entry.deviceDate { |
| 839 | ) -> (settings: SyncedMonitoringSettings, hadConflict: Bool) { |
896 | // A fetch that resumed from a change token only returns what |
| 840 | let winner = lhs.updatedAt >= rhs.updatedAt ? lhs : rhs |
897 | // changed, and a read-only shared row is never pushed, so a row |
| 841 | var merged = winner |
898 | // can appear in neither list. Keeping the date already recorded |
| 842 | |
899 | // for it is what stops it from looking like a local change this |
| 843 | if merged.settings.isEnabled && !defaults.bool(forKey: StorageKey.monitoringLocalActivationConfirmed) { |
900 | // device never pushed. |
| 844 | merged.settings.isEnabled = false |
901 | authority[entry.recordName] = carried |
| 845 | } |
902 | } |
| 846 | |
| |
| 847 | if merged.settings.alertsEnabled { |
| |
| 848 | merged.settings.alertsEnabled = false |
| |
| 849 | } |
903 | } |
| 850 | |
904 | |
| 851 | merged.updatedAt = max(lhs.updatedAt, rhs.updatedAt) |
905 | if let data = try? encoder.encode(authority) { |
| 852 | return (merged, lhs.settings != rhs.settings || lhs.updatedAt != rhs.updatedAt) |
906 | defaults.set(data, forKey: StorageKey.rowAuthority) |
| 853 | } |
| |
| 854 | |
| |
| 855 | private func applyTrackedDomainTombstones(_ trackedDomains: [TrackedDomain], tombstones: [SyncTombstone]) -> [TrackedDomain] { |
| |
| 856 | let tombstonesByDomain = Dictionary(uniqueKeysWithValues: tombstones.compactMap { tombstone -> (String, SyncTombstone)? in |
| |
| 857 | guard tombstone.entityType == .trackedDomain else { return nil } |
| |
| 858 | return (tombstone.identifier, tombstone) |
| |
| 859 | }) |
| |
| 860 | |
| |
| 861 | return trackedDomains.filter { trackedDomain in |
| |
| 862 | let key = Self.normalizeDomain(trackedDomain.domain) |
| |
| 863 | guard let tombstone = tombstonesByDomain[key] else { return true } |
| |
| 864 | return trackedDomain.updatedAt > tombstone.deletedAt |
| |
| 865 | } |
907 | } |
| 866 | } |
908 | } |
| 867 | |
909 | |
| 868 | private func applyWorkflowTombstones(_ workflows: [DomainWorkflow], tombstones: [SyncTombstone]) -> [DomainWorkflow] { |
910 | private func rowDates(in payload: SyncPayload) -> [(recordName: String, deviceDate: Date, serverDate: Date?)] { |
| 869 | let tombstonesByIdentifier = Dictionary(uniqueKeysWithValues: tombstones.compactMap { tombstone -> (String, SyncTombstone)? in |
911 | var entries: [(recordName: String, deviceDate: Date, serverDate: Date?)] = [ |
| 870 | guard tombstone.entityType == .workflow else { return nil } |
912 | (appSettingsRecordName, payload.appSettings.value.updatedAt, payload.appSettings.orderKey.serverDate), |
| 871 | return (tombstone.identifier, tombstone) |
913 | (monitoringSettingsRecordName, payload.monitoringSettings.value.updatedAt, payload.monitoringSettings.orderKey.serverDate) |
| 872 | }) |
914 | ] |
| 873 | |
915 | |
| 874 | return workflows.filter { workflow in |
916 | for row in payload.trackedDomains { |
| 875 | guard let tombstone = tombstonesByIdentifier[workflow.id.uuidString] else { return true } |
917 | entries.append(( |
| 876 | return workflow.updatedAt > tombstone.deletedAt |
918 | trackedDomainRecordName(for: CloudSyncMerge.normalizeDomain(row.value.domain)), |
| |
919 | row.value.updatedAt, |
| |
920 | row.orderKey.serverDate |
| |
921 | )) |
| 877 | } |
922 | } |
| 878 | } |
923 | for row in payload.workflows { |
| 879 | |
924 | entries.append((workflowRecordName(for: row.value.id.uuidString), row.value.updatedAt, row.orderKey.serverDate)) |
| 880 | private func applyNotes( |
| |
| 881 | _ notesByDomain: [String: SyncedDomainNote], |
| |
| 882 | to trackedDomains: [TrackedDomain], |
| |
| 883 | tombstones: [SyncTombstone] |
| |
| 884 | ) -> [TrackedDomain] { |
| |
| 885 | let tombstonesByDomain = Dictionary(uniqueKeysWithValues: tombstones.compactMap { tombstone -> (String, SyncTombstone)? in |
| |
| 886 | guard tombstone.entityType == .trackedDomain else { return nil } |
| |
| 887 | return (tombstone.identifier, tombstone) |
| |
| 888 | }) |
| |
| 889 | |
| |
| 890 | return trackedDomains.map { trackedDomain in |
| |
| 891 | guard trackedDomain.collaboration?.scope != .sharedDatabase else { return trackedDomain } |
| |
| 892 | let normalized = Self.normalizeDomain(trackedDomain.domain) |
| |
| 893 | guard let note = notesByDomain[normalized] else { return trackedDomain } |
| |
| 894 | if let tombstone = tombstonesByDomain[normalized], tombstone.deletedAt >= note.updatedAt { |
| |
| 895 | return trackedDomain |
| |
| 896 | } |
| |
| 897 | |
| |
| 898 | var updated = trackedDomain |
| |
| 899 | updated.note = emptyToNil(note.text) |
| |
| 900 | return updated |
| |
| 901 | } |
925 | } |
| 902 | } |
926 | for row in payload.notesByDomain.values { |
| 903 | |
927 | entries.append((domainNoteRecordName(for: row.value.domain), row.value.updatedAt, row.orderKey.serverDate)) |
| 904 | private func applyHistoryMetadata( |
| |
| 905 | _ historyMetadataByDomain: [String: SyncedHistoryMetadata], |
| |
| 906 | to trackedDomains: [TrackedDomain], |
| |
| 907 | tombstones: [SyncTombstone] |
| |
| 908 | ) -> [TrackedDomain] { |
| |
| 909 | let tombstonesByDomain = Dictionary(uniqueKeysWithValues: tombstones.compactMap { tombstone -> (String, SyncTombstone)? in |
| |
| 910 | guard tombstone.entityType == .trackedDomain else { return nil } |
| |
| 911 | return (tombstone.identifier, tombstone) |
| |
| 912 | }) |
| |
| 913 | |
| |
| 914 | return trackedDomains.map { trackedDomain in |
| |
| 915 | guard trackedDomain.collaboration?.scope != .sharedDatabase else { return trackedDomain } |
| |
| 916 | let normalized = Self.normalizeDomain(trackedDomain.domain) |
| |
| 917 | guard let metadata = historyMetadataByDomain[normalized] else { return trackedDomain } |
| |
| 918 | if let tombstone = tombstonesByDomain[normalized], tombstone.deletedAt >= metadata.updatedAt { |
| |
| 919 | return trackedDomain |
| |
| 920 | } |
| |
| 921 | |
| |
| 922 | var updated = trackedDomain |
| |
| 923 | updated.lastKnownAvailability = metadata.lastKnownAvailabilityRawValue.flatMap(DomainAvailabilityStatus.init(rawValue:)) |
| |
| 924 | updated.lastChangeSeverity = metadata.lastChangeSeverityRawValue.flatMap(ChangeSeverity.init(rawValue:)) |
| |
| 925 | updated.certificateWarningLevel = CertificateWarningLevel(rawValue: metadata.certificateWarningLevelRawValue) ?? .none |
| |
| 926 | updated.certificateDaysRemaining = metadata.certificateDaysRemaining |
| |
| 927 | |
| |
| 928 | if let message = metadata.lastChangeMessage?.trimmingCharacters(in: .whitespacesAndNewlines), !message.isEmpty { |
| |
| 929 | updated.lastChangeSummary = DomainChangeSummary( |
| |
| 930 | hasChanges: true, |
| |
| 931 | changedSections: [], |
| |
| 932 | message: message, |
| |
| 933 | severity: updated.lastChangeSeverity ?? .medium, |
| |
| 934 | impactClassification: .warning, |
| |
| 935 | generatedAt: metadata.lastObservedAt ?? metadata.updatedAt |
| |
| 936 | ) |
| |
| 937 | } |
| |
| 938 | |
| |
| 939 | return updated |
| |
| 940 | } |
928 | } |
| 941 | } |
929 | for row in payload.historyMetadataByDomain.values { |
| 942 | |
930 | entries.append((historyMetadataRecordName(for: row.value.domain), row.value.updatedAt, row.orderKey.serverDate)) |
| 943 | private func latestTombstones(_ tombstones: [SyncTombstone]) -> [SyncTombstone] { |
| |
| 944 | var latest: [String: SyncTombstone] = [:] |
| |
| 945 | |
| |
| 946 | for tombstone in tombstones { |
| |
| 947 | let key = "\(tombstone.entityType.rawValue):\(tombstone.identifier)" |
| |
| 948 | if let existing = latest[key] { |
| |
| 949 | latest[key] = existing.deletedAt >= tombstone.deletedAt ? existing : tombstone |
| |
| 950 | } else { |
| |
| 951 | latest[key] = tombstone |
| |
| 952 | } |
| |
| 953 | } |
931 | } |
| 954 | |
932 | for row in payload.tombstones { |
| 955 | return latest.values.sorted { $0.deletedAt > $1.deletedAt } |
933 | entries.append(( |
| 956 | } |
934 | tombstoneRecordName(for: row.value.entityType, identifier: row.value.identifier), |
| 957 | |
935 | row.value.deletedAt, |
| 958 | private func saveTombstone(_ tombstone: SyncTombstone) { |
936 | row.orderKey.serverDate |
| 959 | var tombstones = loadTombstones() |
937 | )) |
| 960 | tombstones.append(tombstone) |
| |
| 961 | saveTombstones(latestTombstones(tombstones)) |
| |
| 962 | } |
| |
| 963 | |
| |
| 964 | private func loadTombstones() -> [SyncTombstone] { |
| |
| 965 | guard let data = defaults.data(forKey: StorageKey.tombstones), |
| |
| 966 | let tombstones = try? decoder.decode([SyncTombstone].self, from: data) else { |
| |
| 967 | return [] |
| |
| 968 | } |
938 | } |
| 969 | return tombstones |
| |
| 970 | } |
| |
| 971 | |
939 | |
| 972 | private func saveTombstones(_ tombstones: [SyncTombstone]) { |
940 | return entries |
| 973 | if let data = try? encoder.encode(Array(tombstones.prefix(200))) { |
| |
| 974 | defaults.set(data, forKey: StorageKey.tombstones) |
| |
| 975 | } |
| |
| 976 | } |
941 | } |
| 977 | |
942 | |
| 978 | private func loadNoteUpdatedAtByDomain() -> [String: Date] { |
943 | private func loadNoteUpdatedAtByDomain() -> [String: Date] { |
| @@ -1048,10 +1013,12 @@ final class CloudSyncService { |
| 1048 | /// on a brand-new zone. The private database holds the user's own records in |
1013 | /// on a brand-new zone. The private database holds the user's own records in |
| 1049 | /// a single custom zone; the shared database exposes one zone per accepted |
1014 | /// a single custom zone; the shared database exposes one zone per accepted |
| 1050 | /// share, so every shared zone is fetched. |
1015 | /// share, so every shared zone is fetched. |
| 1051 | private func fetchZoneRecords(in scope: SyncDatabaseScope) async throws -> [CKRecord] { |
1016 | private func fetchZoneRecords( |
| |
1017 | in scope: SyncDatabaseScope |
| |
1018 | ) async throws -> (records: [CKRecord], changeTokens: [String: CKServerChangeToken]) { |
| 1052 | guard let database = cloudKitDatabase(in: scope) else { |
1019 | guard let database = cloudKitDatabase(in: scope) else { |
| 1053 | if scope == .sharedDatabase { |
1020 | if scope == .sharedDatabase { |
| 1054 | return [] |
1021 | return ([], [:]) |
| 1055 | } |
1022 | } |
| 1056 | throw CloudSyncRuntimeError.missingEntitlement |
1023 | throw CloudSyncRuntimeError.missingEntitlement |
| 1057 | } |
1024 | } |
| @@ -1065,31 +1032,48 @@ final class CloudSyncService { |
| 1065 | zoneIDs = try await database.allRecordZones().map(\.zoneID) |
1032 | zoneIDs = try await database.allRecordZones().map(\.zoneID) |
| 1066 | } |
1033 | } |
| 1067 | |
1034 | |
| 1068 | guard !zoneIDs.isEmpty else { return [] } |
1035 | guard !zoneIDs.isEmpty else { return ([], [:]) } |
| 1069 | return try await fetchZoneChanges(in: database, zoneIDs: zoneIDs) |
1036 | return try await fetchZoneChanges(in: database, scope: scope, zoneIDs: zoneIDs) |
| 1070 | } |
1037 | } |
| 1071 | |
1038 | |
| 1072 | private func fetchZoneChanges(in database: CKDatabase, zoneIDs: [CKRecordZone.ID]) async throws -> [CKRecord] { |
1039 | /// Fetches what changed in each zone since the token stored for it, and |
| 1073 | // A nil change token requests every record in the zone. The server may |
1040 | /// returns the tokens the caller should store once the changes are safely |
| 1074 | // truncate a large response and set `moreComing`, so keep re-fetching |
1041 | /// applied. A zone with no stored token is fetched in full. |
| 1075 | // the still-truncated zones with their latest tokens until all drain. |
1042 | /// |
| 1076 | var tokensByZone: [CKRecordZone.ID: CKServerChangeToken?] = [:] |
1043 | /// The server may truncate a large response and set `moreComing`, so keep |
| |
1044 | /// re-fetching the still-truncated zones with their latest tokens until all |
| |
1045 | /// drain. A token the server has aged out comes back as |
| |
1046 | /// `.changeTokenExpired`, and the only recovery is to drop it and refetch |
| |
1047 | /// that zone in full; that is done at most once per zone per sync, so a |
| |
1048 | /// token that keeps expiring cannot spin here. |
| |
1049 | private func fetchZoneChanges( |
| |
1050 | in database: CKDatabase, |
| |
1051 | scope: SyncDatabaseScope, |
| |
1052 | zoneIDs: [CKRecordZone.ID] |
| |
1053 | ) async throws -> (records: [CKRecord], changeTokens: [String: CKServerChangeToken]) { |
| |
1054 | var pendingByZone: [CKRecordZone.ID: CKServerChangeToken?] = [:] |
| 1077 | for zoneID in zoneIDs { |
1055 | for zoneID in zoneIDs { |
| 1078 | tokensByZone[zoneID] = .some(nil) |
1056 | pendingByZone[zoneID] = .some(loadChangeToken(forKey: changeTokenStorageKey(scope: scope, zoneID: zoneID))) |
| 1079 | } |
1057 | } |
| 1080 | |
1058 | |
| 1081 | var records: [CKRecord] = [] |
1059 | var records: [CKRecord] = [] |
| 1082 | while !tokensByZone.isEmpty { |
1060 | var tokensByZone: [CKRecordZone.ID: CKServerChangeToken] = [:] |
| 1083 | tokensByZone = try await withCheckedThrowingContinuation { continuation in |
1061 | var refetchedAfterExpiry: Set<CKRecordZone.ID> = [] |
| |
1062 | |
| |
1063 | while !pendingByZone.isEmpty { |
| |
1064 | let step: ZoneChangesStep = try await withCheckedThrowingContinuation { continuation in |
| 1084 | var moreByZone: [CKRecordZone.ID: CKServerChangeToken?] = [:] |
1065 | var moreByZone: [CKRecordZone.ID: CKServerChangeToken?] = [:] |
| 1085 | let configurations = tokensByZone.mapValues { token -> CKFetchRecordZoneChangesOperation.ZoneConfiguration in |
1066 | var fetchedByZone: [CKRecordZone.ID: CKServerChangeToken] = [:] |
| |
1067 | var expiredZones: [CKRecordZone.ID] = [] |
| |
1068 | |
| |
1069 | let configurations = pendingByZone.mapValues { token -> CKFetchRecordZoneChangesOperation.ZoneConfiguration in |
| 1086 | let configuration = CKFetchRecordZoneChangesOperation.ZoneConfiguration() |
1070 | let configuration = CKFetchRecordZoneChangesOperation.ZoneConfiguration() |
| 1087 | configuration.previousServerChangeToken = token ?? nil |
1071 | configuration.previousServerChangeToken = token ?? nil |
| 1088 | return configuration |
1072 | return configuration |
| 1089 | } |
1073 | } |
| 1090 | |
1074 | |
| 1091 | let operation = CKFetchRecordZoneChangesOperation( |
1075 | let operation = CKFetchRecordZoneChangesOperation( |
| 1092 | recordZoneIDs: Array(tokensByZone.keys), |
1076 | recordZoneIDs: Array(pendingByZone.keys), |
| 1093 | configurationsByRecordZoneID: configurations |
1077 | configurationsByRecordZoneID: configurations |
| 1094 | ) |
1078 | ) |
| 1095 | operation.recordWasChangedBlock = { _, result in |
1079 | operation.recordWasChangedBlock = { _, result in |
| @@ -1098,31 +1082,89 @@ final class CloudSyncService { |
| 1098 | } |
1082 | } |
| 1099 | } |
1083 | } |
| 1100 | operation.recordZoneFetchResultBlock = { zoneID, result in |
1084 | operation.recordZoneFetchResultBlock = { zoneID, result in |
| 1101 | if case .success(let value) = result, value.moreComing { |
1085 | switch result { |
| 1102 | moreByZone[zoneID] = .some(value.serverChangeToken) |
1086 | case .success(let value): |
| |
1087 | fetchedByZone[zoneID] = value.serverChangeToken |
| |
1088 | if value.moreComing { |
| |
1089 | moreByZone[zoneID] = .some(value.serverChangeToken) |
| |
1090 | } |
| |
1091 | case .failure(let error): |
| |
1092 | if (error as? CKError)?.code == .changeTokenExpired { |
| |
1093 | expiredZones.append(zoneID) |
| |
1094 | } |
| 1103 | } |
1095 | } |
| 1104 | } |
1096 | } |
| 1105 | operation.fetchRecordZoneChangesResultBlock = { result in |
1097 | operation.fetchRecordZoneChangesResultBlock = { result in |
| 1106 | switch result { |
1098 | switch result { |
| 1107 | case .success: |
1099 | case .success: |
| 1108 | continuation.resume(returning: moreByZone) |
1100 | continuation.resume( |
| |
1101 | returning: ZoneChangesStep(pendingByZone: moreByZone, tokensByZone: fetchedByZone, expiredZones: expiredZones) |
| |
1102 | ) |
| 1109 | case .failure(let error): |
1103 | case .failure(let error): |
| 1110 | continuation.resume(throwing: error) |
1104 | // An expired token is reported per zone and also fails |
| |
1105 | // the operation as a whole. That is the one failure the |
| |
1106 | // loop can recover from, and only when a zone actually |
| |
1107 | // reported it — anything else still throws. |
| |
1108 | let code = (error as? CKError)?.code |
| |
1109 | if !expiredZones.isEmpty, code == .partialFailure || code == .changeTokenExpired { |
| |
1110 | continuation.resume( |
| |
1111 | returning: ZoneChangesStep(pendingByZone: moreByZone, tokensByZone: fetchedByZone, expiredZones: expiredZones) |
| |
1112 | ) |
| |
1113 | } else { |
| |
1114 | continuation.resume(throwing: error) |
| |
1115 | } |
| 1111 | } |
1116 | } |
| 1112 | } |
1117 | } |
| 1113 | database.add(operation) |
1118 | database.add(operation) |
| 1114 | } |
1119 | } |
| |
1120 | |
| |
1121 | tokensByZone.merge(step.tokensByZone) { _, fetched in fetched } |
| |
1122 | pendingByZone = step.pendingByZone |
| |
1123 | |
| |
1124 | for zoneID in step.expiredZones where !refetchedAfterExpiry.contains(zoneID) { |
| |
1125 | refetchedAfterExpiry.insert(zoneID) |
| |
1126 | tokensByZone.removeValue(forKey: zoneID) |
| |
1127 | pendingByZone[zoneID] = .some(nil) |
| |
1128 | } |
| |
1129 | } |
| |
1130 | |
| |
1131 | let changeTokens = tokensByZone.reduce(into: [String: CKServerChangeToken]()) { partialResult, entry in |
| |
1132 | partialResult[changeTokenStorageKey(scope: scope, zoneID: entry.key)] = entry.value |
| 1115 | } |
1133 | } |
| |
1134 | return (records, changeTokens) |
| |
1135 | } |
| |
1136 | |
| |
1137 | private func changeTokenStorageKey(scope: SyncDatabaseScope, zoneID: CKRecordZone.ID) -> String { |
| |
1138 | let scopeName = scope == .privateDatabase ? "private" : "shared" |
| |
1139 | return "\(StorageKey.changeTokenPrefix)\(scopeName).\(zoneID.ownerName).\(zoneID.zoneName)" |
| |
1140 | } |
| |
1141 | |
| |
1142 | private func loadChangeToken(forKey key: String) -> CKServerChangeToken? { |
| |
1143 | guard let data = defaults.data(forKey: key) else { return nil } |
| |
1144 | return try? NSKeyedUnarchiver.unarchivedObject(ofClass: CKServerChangeToken.self, from: data) |
| |
1145 | } |
| 1116 | |
1146 | |
| 1117 | return records |
1147 | private func commitChangeTokens(_ changeTokens: [String: CKServerChangeToken]) { |
| |
1148 | for (key, token) in changeTokens { |
| |
1149 | guard let data = try? NSKeyedArchiver.archivedData(withRootObject: token, requiringSecureCoding: true) else { continue } |
| |
1150 | defaults.set(data, forKey: key) |
| |
1151 | } |
| 1118 | } |
1152 | } |
| 1119 | |
1153 | |
| 1120 | private func decodeRecords<T: Decodable>(_ records: [CKRecord], ofType recordType: String) -> [T] { |
1154 | /// Decodes the payload blob and pairs it with the record's server-assigned |
| 1121 | var results: [T] = [] |
1155 | /// modification date, which is what the merge orders conflicts by. The |
| |
1156 | /// `deviceDate` key path names the payload's own date, kept as display |
| |
1157 | /// metadata. |
| |
1158 | private func decodeRecords<T: Decodable>( |
| |
1159 | _ records: [CKRecord], |
| |
1160 | ofType recordType: String, |
| |
1161 | deviceDate: KeyPath<T, Date> |
| |
1162 | ) -> [SyncRow<T>] { |
| |
1163 | var results: [SyncRow<T>] = [] |
| 1122 | for record in records where record.recordType == recordType { |
1164 | for record in records where record.recordType == recordType { |
| 1123 | guard let payload = record[CloudRecordKey.payload] as? Data else { continue } |
1165 | guard let payload = record[CloudRecordKey.payload] as? Data else { continue } |
| 1124 | if let decoded = try? decoder.decode(T.self, from: payload) { |
1166 | if let decoded = try? decoder.decode(T.self, from: payload) { |
| 1125 | results.append(decoded) |
1167 | results.append(SyncRow(value: decoded, orderKey: Self.orderKey(for: record, deviceDate: decoded[keyPath: deviceDate]))) |
| 1126 | } else { |
1168 | } else { |
| 1127 | lastErrorMessage = "Some iCloud records were skipped because they could not be decoded." |
1169 | lastErrorMessage = "Some iCloud records were skipped because they could not be decoded." |
| 1128 | } |
1170 | } |
| @@ -1130,7 +1172,15 @@ final class CloudSyncService { |
| 1130 | return results |
1172 | return results |
| 1131 | } |
1173 | } |
| 1132 | |
1174 | |
| 1133 | private func trackedDomains(from records: [CKRecord], in scope: SyncDatabaseScope) async throws -> [TrackedDomain] { |
1175 | /// `modificationDate` is nil only on a `CKRecord` the server has never |
| |
1176 | /// stored, which a fetched record never is. A nil would read as an unpushed |
| |
1177 | /// local change, so a record arriving without one is left to win, matching |
| |
1178 | /// how the rest of the merge treats an unknown server date. |
| |
1179 | private static func orderKey(for record: CKRecord, deviceDate: Date) -> SyncOrderKey { |
| |
1180 | SyncOrderKey(serverDate: record.modificationDate, deviceDate: deviceDate) |
| |
1181 | } |
| |
1182 | |
| |
1183 | private func trackedDomains(from records: [CKRecord], in scope: SyncDatabaseScope) async throws -> [SyncRow<TrackedDomain>] { |
| 1134 | let matching = records.filter { $0.recordType == CloudRecordType.trackedDomain } |
1184 | let matching = records.filter { $0.recordType == CloudRecordType.trackedDomain } |
| 1135 | let shares = try await sharesByRecordID(for: matching, in: scope) |
1185 | let shares = try await sharesByRecordID(for: matching, in: scope) |
| 1136 | |
1186 | |
| @@ -1140,13 +1190,13 @@ final class CloudSyncService { |
| 1140 | lastErrorMessage = "Some iCloud records were skipped because they could not be decoded." |
1190 | lastErrorMessage = "Some iCloud records were skipped because they could not be decoded." |
| 1141 | return nil |
1191 | return nil |
| 1142 | } |
1192 | } |
| 1143 | var trackedDomain = Self.payloadTrackedDomain(decoded) |
1193 | var trackedDomain = CloudSyncMerge.payloadTrackedDomain(decoded) |
| 1144 | trackedDomain.collaboration = collaborationMetadata(for: record, share: shares[record.recordID], scope: scope) |
1194 | trackedDomain.collaboration = collaborationMetadata(for: record, share: shares[record.recordID], scope: scope) |
| 1145 | return trackedDomain |
1195 | return SyncRow(value: trackedDomain, orderKey: Self.orderKey(for: record, deviceDate: trackedDomain.updatedAt)) |
| 1146 | } |
1196 | } |
| 1147 | } |
1197 | } |
| 1148 | |
1198 | |
| 1149 | private func workflows(from records: [CKRecord], in scope: SyncDatabaseScope) async throws -> [DomainWorkflow] { |
1199 | private func workflows(from records: [CKRecord], in scope: SyncDatabaseScope) async throws -> [SyncRow<DomainWorkflow>] { |
| 1150 | let matching = records.filter { $0.recordType == CloudRecordType.workflow } |
1200 | let matching = records.filter { $0.recordType == CloudRecordType.workflow } |
| 1151 | let shares = try await sharesByRecordID(for: matching, in: scope) |
1201 | let shares = try await sharesByRecordID(for: matching, in: scope) |
| 1152 | |
1202 | |
| @@ -1156,9 +1206,9 @@ final class CloudSyncService { |
| 1156 | lastErrorMessage = "Some iCloud records were skipped because they could not be decoded." |
1206 | lastErrorMessage = "Some iCloud records were skipped because they could not be decoded." |
| 1157 | return nil |
1207 | return nil |
| 1158 | } |
1208 | } |
| 1159 | var workflow = normalizedWorkflow(decoded) |
1209 | var workflow = CloudSyncMerge.normalizedWorkflow(decoded) |
| 1160 | workflow.collaboration = collaborationMetadata(for: record, share: shares[record.recordID], scope: scope) |
1210 | workflow.collaboration = collaborationMetadata(for: record, share: shares[record.recordID], scope: scope) |
| 1161 | return workflow |
1211 | return SyncRow(value: workflow, orderKey: Self.orderKey(for: record, deviceDate: workflow.updatedAt)) |
| 1162 | } |
1212 | } |
| 1163 | } |
1213 | } |
| 1164 | |
1214 | |
| @@ -1225,9 +1275,9 @@ final class CloudSyncService { |
| 1225 | private func shareRecordName(for entity: ShareableEntity) async throws -> String? { |
1275 | private func shareRecordName(for entity: ShareableEntity) async throws -> String? { |
| 1226 | switch entity { |
1276 | switch entity { |
| 1227 | case .trackedDomain(let domain): |
1277 | case .trackedDomain(let domain): |
| 1228 | let normalized = Self.normalizeDomain(domain) |
1278 | let normalized = CloudSyncMerge.normalizeDomain(domain) |
| 1229 | return DomainDataPortabilityService.loadTrackedDomains() |
1279 | return DomainDataPortabilityService.loadTrackedDomains() |
| 1230 | .first(where: { Self.normalizeDomain($0.domain) == normalized })? |
1280 | .first(where: { CloudSyncMerge.normalizeDomain($0.domain) == normalized })? |
| 1231 | .collaboration?.shareRecordName |
1281 | .collaboration?.shareRecordName |
| 1232 | case .workflow(let identifier): |
1282 | case .workflow(let identifier): |
| 1233 | return DomainDataPortabilityService.loadWorkflows() |
1283 | return DomainDataPortabilityService.loadWorkflows() |
| @@ -1237,8 +1287,8 @@ final class CloudSyncService { |
| 1237 | } |
1287 | } |
| 1238 | |
1288 | |
| 1239 | private func makeTrackedDomainRecord(_ trackedDomain: TrackedDomain) -> CKRecord { |
1289 | private func makeTrackedDomainRecord(_ trackedDomain: TrackedDomain) -> CKRecord { |
| 1240 | let normalized = Self.normalizeDomain(trackedDomain.domain) |
1290 | let normalized = CloudSyncMerge.normalizeDomain(trackedDomain.domain) |
| 1241 | let sanitized = Self.payloadTrackedDomain(trackedDomain) |
1291 | let sanitized = CloudSyncMerge.payloadTrackedDomain(trackedDomain) |
| 1242 | return makeRecord( |
1292 | return makeRecord( |
| 1243 | type: CloudRecordType.trackedDomain, |
1293 | type: CloudRecordType.trackedDomain, |
| 1244 | recordName: trackedDomainRecordName(for: normalized), |
1294 | recordName: trackedDomainRecordName(for: normalized), |
| @@ -1251,7 +1301,7 @@ final class CloudSyncService { |
| 1251 | } |
1301 | } |
| 1252 | |
1302 | |
| 1253 | private func makeWorkflowRecord(_ workflow: DomainWorkflow) -> CKRecord { |
1303 | private func makeWorkflowRecord(_ workflow: DomainWorkflow) -> CKRecord { |
| 1254 | let normalized = normalizedWorkflow(workflow) |
1304 | let normalized = CloudSyncMerge.normalizedWorkflow(workflow) |
| 1255 | return makeRecord( |
1305 | return makeRecord( |
| 1256 | type: CloudRecordType.workflow, |
1306 | type: CloudRecordType.workflow, |
| 1257 | recordName: workflowRecordName(for: normalized.id.uuidString), |
1307 | recordName: workflowRecordName(for: normalized.id.uuidString), |
| @@ -1266,7 +1316,7 @@ final class CloudSyncService { |
| 1266 | private func makeAppSettingsRecord(_ settings: SyncedAppSettings) -> CKRecord { |
1316 | private func makeAppSettingsRecord(_ settings: SyncedAppSettings) -> CKRecord { |
| 1267 | makeRecord( |
1317 | makeRecord( |
| 1268 | type: CloudRecordType.appSettings, |
1318 | type: CloudRecordType.appSettings, |
| 1269 | recordName: "app-settings", |
1319 | recordName: appSettingsRecordName, |
| 1270 | payload: settings, |
1320 | payload: settings, |
| 1271 | extraFields: [CloudRecordKey.updatedAt: settings.updatedAt as CKRecordValue] |
1321 | extraFields: [CloudRecordKey.updatedAt: settings.updatedAt as CKRecordValue] |
| 1272 | ) |
1322 | ) |
| @@ -1275,7 +1325,7 @@ final class CloudSyncService { |
| 1275 | private func makeMonitoringSettingsRecord(_ settings: SyncedMonitoringSettings) -> CKRecord { |
1325 | private func makeMonitoringSettingsRecord(_ settings: SyncedMonitoringSettings) -> CKRecord { |
| 1276 | makeRecord( |
1326 | makeRecord( |
| 1277 | type: CloudRecordType.monitoringSettings, |
1327 | type: CloudRecordType.monitoringSettings, |
| 1278 | recordName: "monitoring-settings", |
1328 | recordName: monitoringSettingsRecordName, |
| 1279 | payload: settings, |
1329 | payload: settings, |
| 1280 | extraFields: [CloudRecordKey.updatedAt: settings.updatedAt as CKRecordValue] |
1330 | extraFields: [CloudRecordKey.updatedAt: settings.updatedAt as CKRecordValue] |
| 1281 | ) |
1331 | ) |
| @@ -1379,16 +1429,6 @@ final class CloudSyncService { |
| 1379 | case missingLocalItem |
1429 | case missingLocalItem |
| 1380 | } |
1430 | } |
| 1381 | |
1431 | |
| 1382 | private static func normalizeDomain(_ value: String) -> String { |
| |
| 1383 | value |
| |
| 1384 | .trimmingCharacters(in: .whitespacesAndNewlines) |
| |
| 1385 | .replacingOccurrences(of: "https://", with: "") |
| |
| 1386 | .replacingOccurrences(of: "http://", with: "") |
| |
| 1387 | .components(separatedBy: "/") |
| |
| 1388 | .first? |
| |
| 1389 | .lowercased() ?? "" |
| |
| 1390 | } |
| |
| 1391 | |
| |
| 1392 | private func cloudKitContainer() -> CKContainer { |
1432 | private func cloudKitContainer() -> CKContainer { |
| 1393 | if let container { |
1433 | if let container { |
| 1394 | return container |
1434 | return container |
| @@ -1445,156 +1485,12 @@ final class CloudSyncService { |
| 1445 | "This build does not have the CloudKit entitlement required for iCloud sync." |
1485 | "This build does not have the CloudKit entitlement required for iCloud sync." |
| 1446 | } |
1486 | } |
| 1447 | |
1487 | |
| 1448 | private static func payloadTrackedDomain(_ trackedDomain: TrackedDomain) -> TrackedDomain { |
1488 | private var appSettingsRecordName: String { |
| 1449 | TrackedDomain( |
1489 | "app-settings" |
| 1450 | id: trackedDomain.id, |
| |
| 1451 | domain: normalizeDomain(trackedDomain.domain), |
| |
| 1452 | createdAt: trackedDomain.createdAt, |
| |
| 1453 | updatedAt: trackedDomain.updatedAt, |
| |
| 1454 | note: trackedDomain.note, |
| |
| 1455 | isPinned: trackedDomain.isPinned, |
| |
| 1456 | monitoringEnabled: trackedDomain.monitoringEnabled, |
| |
| 1457 | lastKnownAvailability: trackedDomain.lastKnownAvailability, |
| |
| 1458 | lastSnapshotID: nil, |
| |
| 1459 | lastChangeSummary: nil, |
| |
| 1460 | lastChangeSeverity: trackedDomain.lastChangeSeverity, |
| |
| 1461 | certificateWarningLevel: trackedDomain.certificateWarningLevel, |
| |
| 1462 | certificateDaysRemaining: trackedDomain.certificateDaysRemaining, |
| |
| 1463 | lastMonitoredAt: trackedDomain.lastMonitoredAt, |
| |
| 1464 | lastAlertAt: trackedDomain.lastAlertAt, |
| |
| 1465 | monitoringState: trackedDomain.monitoringState, |
| |
| 1466 | pendingMonitoringAlerts: trackedDomain.pendingMonitoringAlerts, |
| |
| 1467 | collaboration: trackedDomain.collaboration |
| |
| 1468 | ) |
| |
| 1469 | } |
| |
| 1470 | |
| |
| 1471 | private func mergedTrackedDomain(_ lhs: TrackedDomain, _ rhs: TrackedDomain) -> TrackedDomain { |
| |
| 1472 | let winner = preferredTrackedDomain(lhs, rhs) |
| |
| 1473 | |
| |
| 1474 | return TrackedDomain( |
| |
| 1475 | id: lhs.id, |
| |
| 1476 | domain: Self.normalizeDomain(lhs.domain.isEmpty ? rhs.domain : lhs.domain), |
| |
| 1477 | createdAt: min(lhs.createdAt, rhs.createdAt), |
| |
| 1478 | updatedAt: max(lhs.updatedAt, rhs.updatedAt), |
| |
| 1479 | note: winner.note ?? lhs.note ?? rhs.note, |
| |
| 1480 | isPinned: winner.isPinned, |
| |
| 1481 | monitoringEnabled: winner.monitoringEnabled, |
| |
| 1482 | lastKnownAvailability: winner.lastKnownAvailability ?? lhs.lastKnownAvailability ?? rhs.lastKnownAvailability, |
| |
| 1483 | lastSnapshotID: nil, |
| |
| 1484 | lastChangeSummary: nil, |
| |
| 1485 | lastChangeSeverity: winner.lastChangeSeverity ?? lhs.lastChangeSeverity ?? rhs.lastChangeSeverity, |
| |
| 1486 | certificateWarningLevel: higherCertificateWarningLevel(lhs.certificateWarningLevel, rhs.certificateWarningLevel), |
| |
| 1487 | certificateDaysRemaining: winner.certificateDaysRemaining ?? lhs.certificateDaysRemaining ?? rhs.certificateDaysRemaining, |
| |
| 1488 | lastMonitoredAt: [lhs.lastMonitoredAt, rhs.lastMonitoredAt].compactMap { $0 }.max(), |
| |
| 1489 | lastAlertAt: [lhs.lastAlertAt, rhs.lastAlertAt].compactMap { $0 }.max(), |
| |
| 1490 | monitoringState: preferredMonitoringState(lhs.monitoringState, rhs.monitoringState), |
| |
| 1491 | pendingMonitoringAlerts: deduplicatedPendingAlerts(lhs.pendingMonitoringAlerts + rhs.pendingMonitoringAlerts), |
| |
| 1492 | collaboration: preferredCollaboration(lhs.collaboration, rhs.collaboration) |
| |
| 1493 | ) |
| |
| 1494 | } |
| |
| 1495 | |
| |
| 1496 | private func normalizedWorkflow(_ workflow: DomainWorkflow) -> DomainWorkflow { |
| |
| 1497 | DomainWorkflow( |
| |
| 1498 | id: workflow.id, |
| |
| 1499 | name: workflow.name.trimmingCharacters(in: .whitespacesAndNewlines), |
| |
| 1500 | domains: deduplicated(workflow.domains.map(Self.normalizeDomain).filter { !$0.isEmpty }), |
| |
| 1501 | createdAt: workflow.createdAt, |
| |
| 1502 | updatedAt: workflow.updatedAt, |
| |
| 1503 | notes: emptyToNil(workflow.notes ?? ""), |
| |
| 1504 | collaboration: workflow.collaboration |
| |
| 1505 | ) |
| |
| 1506 | } |
| |
| 1507 | |
| |
| 1508 | private func preferredTrackedDomain(_ lhs: TrackedDomain, _ rhs: TrackedDomain) -> TrackedDomain { |
| |
| 1509 | let lhsRank = collaborationRank(lhs.collaboration) |
| |
| 1510 | let rhsRank = collaborationRank(rhs.collaboration) |
| |
| 1511 | if lhsRank != rhsRank { |
| |
| 1512 | return lhsRank > rhsRank ? lhs : rhs |
| |
| 1513 | } |
| |
| 1514 | return lhs.updatedAt >= rhs.updatedAt ? lhs : rhs |
| |
| 1515 | } |
| |
| 1516 | |
| |
| 1517 | private func preferredMonitoringState(_ lhs: MonitoringState, _ rhs: MonitoringState) -> MonitoringState { |
| |
| 1518 | let lhsDate = [lhs.lastCheck, lhs.lastAlertDate, lhs.lastChangeDate].compactMap { $0 }.max() ?? .distantPast |
| |
| 1519 | let rhsDate = [rhs.lastCheck, rhs.lastAlertDate, rhs.lastChangeDate].compactMap { $0 }.max() ?? .distantPast |
| |
| 1520 | return lhsDate >= rhsDate ? lhs : rhs |
| |
| 1521 | } |
| |
| 1522 | |
| |
| 1523 | private func deduplicatedPendingAlerts(_ alerts: [MonitoringPendingAlert]) -> [MonitoringPendingAlert] { |
| |
| 1524 | var uniqueByHash: [String: MonitoringPendingAlert] = [:] |
| |
| 1525 | for alert in alerts { |
| |
| 1526 | if let existing = uniqueByHash[alert.changeHash] { |
| |
| 1527 | uniqueByHash[alert.changeHash] = existing.detectedAt >= alert.detectedAt ? existing : alert |
| |
| 1528 | } else { |
| |
| 1529 | uniqueByHash[alert.changeHash] = alert |
| |
| 1530 | } |
| |
| 1531 | } |
| |
| 1532 | return uniqueByHash.values.sorted { $0.detectedAt < $1.detectedAt } |
| |
| 1533 | } |
| |
| 1534 | |
| |
| 1535 | private func preferredWorkflow(_ lhs: DomainWorkflow, _ rhs: DomainWorkflow) -> DomainWorkflow { |
| |
| 1536 | let lhsRank = collaborationRank(lhs.collaboration) |
| |
| 1537 | let rhsRank = collaborationRank(rhs.collaboration) |
| |
| 1538 | if lhsRank != rhsRank { |
| |
| 1539 | return lhsRank > rhsRank ? lhs : rhs |
| |
| 1540 | } |
| |
| 1541 | return lhs.updatedAt >= rhs.updatedAt ? lhs : rhs |
| |
| 1542 | } |
| |
| 1543 | |
| |
| 1544 | private func preferredCollaboration( |
| |
| 1545 | _ lhs: CollaborationMetadata?, |
| |
| 1546 | _ rhs: CollaborationMetadata? |
| |
| 1547 | ) -> CollaborationMetadata? { |
| |
| 1548 | guard let lhs else { return rhs } |
| |
| 1549 | guard let rhs else { return lhs } |
| |
| 1550 | let lhsRank = collaborationRank(lhs) |
| |
| 1551 | let rhsRank = collaborationRank(rhs) |
| |
| 1552 | if lhsRank != rhsRank { |
| |
| 1553 | return lhsRank > rhsRank ? lhs : rhs |
| |
| 1554 | } |
| |
| 1555 | if lhs.shareRecordName != nil { |
| |
| 1556 | return lhs |
| |
| 1557 | } |
| |
| 1558 | return rhs |
| |
| 1559 | } |
| |
| 1560 | |
| |
| 1561 | private func collaborationRank(_ collaboration: CollaborationMetadata?) -> Int { |
| |
| 1562 | guard let collaboration else { return 0 } |
| |
| 1563 | switch collaboration.ownership { |
| |
| 1564 | case .owner: |
| |
| 1565 | return collaboration.isShared ? 3 : 2 |
| |
| 1566 | case .participant: |
| |
| 1567 | return collaboration.permission == .editable ? 1 : 0 |
| |
| 1568 | } |
| |
| 1569 | } |
| |
| 1570 | |
| |
| 1571 | private func emptyToNil(_ value: String) -> String? { |
| |
| 1572 | let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) |
| |
| 1573 | return trimmed.isEmpty ? nil : trimmed |
| |
| 1574 | } |
| |
| 1575 | |
| |
| 1576 | private func sameAppSettings(_ lhs: AppSettingsSnapshot, _ rhs: AppSettingsSnapshot) -> Bool { |
| |
| 1577 | lhs.recentSearches == rhs.recentSearches |
| |
| 1578 | && lhs.savedDomains == rhs.savedDomains |
| |
| 1579 | && lhs.resolverURLString == rhs.resolverURLString |
| |
| 1580 | && lhs.appDensityRawValue == rhs.appDensityRawValue |
| |
| 1581 | } |
1490 | } |
| 1582 | |
1491 | |
| 1583 | private func deduplicated(_ values: [String]) -> [String] { |
1492 | private var monitoringSettingsRecordName: String { |
| 1584 | var seen = Set<String>() |
1493 | "monitoring-settings" |
| 1585 | return values.filter { seen.insert($0).inserted } |
| |
| 1586 | } |
| |
| 1587 | |
| |
| 1588 | private func higherCertificateWarningLevel( |
| |
| 1589 | _ lhs: CertificateWarningLevel, |
| |
| 1590 | _ rhs: CertificateWarningLevel |
| |
| 1591 | ) -> CertificateWarningLevel { |
| |
| 1592 | let rank: [CertificateWarningLevel: Int] = [ |
| |
| 1593 | .none: 0, |
| |
| 1594 | .warning: 1, |
| |
| 1595 | .critical: 2 |
| |
| 1596 | ] |
| |
| 1597 | return (rank[lhs] ?? 0) >= (rank[rhs] ?? 0) ? lhs : rhs |
| |
| 1598 | } |
1494 | } |
| 1599 | |
1495 | |
| 1600 | private func trackedDomainRecordName(for normalizedDomain: String) -> String { |
1496 | private func trackedDomainRecordName(for normalizedDomain: String) -> String { |