Commit eed2feb5f7
Verified · cmc
Layout: unified · split
DomainDig/CloudSyncService.swift +128 −29
| @@ -90,6 +90,22 @@ private struct SyncPayload { | ||
| 90 | 90 | var tombstones: [SyncRow<SyncTombstone>] |
| 91 | 91 | } |
| 92 | 92 | |
| 93 | /// What a remote fetch produced: the payload, and the change token each zone | |
| 94 | /// may resume from once the payload has been merged and pushed. | |
| 95 | private struct RemoteSyncState { | |
| 96 | var payload: SyncPayload | |
| 97 | var changeTokens: [String: CKServerChangeToken] | |
| 98 | } | |
| 99 | ||
| 100 | /// One pass of `CKFetchRecordZoneChangesOperation`: the zones that still have | |
| 101 | /// more coming, the token each zone reached, and the zones whose stored token | |
| 102 | /// the server has aged out. | |
| 103 | private struct ZoneChangesStep { | |
| 104 | var pendingByZone: [CKRecordZone.ID: CKServerChangeToken?] | |
| 105 | var tokensByZone: [CKRecordZone.ID: CKServerChangeToken] | |
| 106 | var expiredZones: [CKRecordZone.ID] | |
| 107 | } | |
| 108 | ||
| 93 | 109 | /// The server date this device last saw for a record, with the payload date the |
| 94 | 110 | /// row carried at that moment. A row whose payload date has moved since has a |
| 95 | 111 | /// local change the server has not seen. |
| @@ -146,6 +162,7 @@ final class CloudSyncService { | ||
| 146 | 162 | static let tombstones = "cloudSync.tombstones" |
| 147 | 163 | static let monitoringLocalActivationConfirmed = "cloudSync.monitoringLocalActivationConfirmed" |
| 148 | 164 | static let rowAuthority = "cloudSync.rowAuthority" |
| 165 | static let changeTokenPrefix = "cloudSync.changeToken." | |
| 149 | 166 | } |
| 150 | 167 | |
| 151 | 168 | private init(defaults: UserDefaults = .standard) { |
| @@ -433,7 +450,7 @@ final class CloudSyncService { | ||
| 433 | 450 | do { |
| 434 | 451 | let local = loadLocalPayload() |
| 435 | 452 | let remote = try await fetchRemotePayload() |
| 436 | let merged = merge(local: local, remote: remote) | |
| 453 | let merged = merge(local: local, remote: remote.payload) | |
| 437 | 454 | applyMergedPayload(merged.payload) |
| 438 | 455 | let pushedServerDates = try await pushMergedPayload(merged.payload) |
| 439 | 456 | |
| @@ -441,7 +458,12 @@ final class CloudSyncService { | ||
| 441 | 458 | // local stores round-trip dates through ISO-8601 and through |
| 442 | 459 | // `JSONEncoder`, and the next sync compares against what they read |
| 443 | 460 | // back, not against the in-memory values. |
| 444 | recordRowAuthority(in: loadLocalPayload(), remote: remote, pushedServerDates: pushedServerDates) | |
| 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) | |
| 445 | 467 | |
| 446 | 468 | lastSyncDate = Date() |
| 447 | 469 | defaults.set(lastSyncDate, forKey: StorageKey.lastSyncDate) |
| @@ -555,9 +577,11 @@ final class CloudSyncService { | ||
| 555 | 577 | ) |
| 556 | 578 | } |
| 557 | 579 | |
| 558 | private func fetchRemotePayload() async throws -> SyncPayload { | |
| 559 | let privateRecords = try await fetchZoneRecords(in: .privateDatabase) | |
| 560 | let sharedRecords = try await fetchZoneRecords(in: .sharedDatabase) | |
| 580 | private func fetchRemotePayload() async throws -> RemoteSyncState { | |
| 581 | let privateFetch = try await fetchZoneRecords(in: .privateDatabase) | |
| 582 | let sharedFetch = try await fetchZoneRecords(in: .sharedDatabase) | |
| 583 | let privateRecords = privateFetch.records | |
| 584 | let sharedRecords = sharedFetch.records | |
| 561 | 585 | |
| 562 | 586 | let privateTrackedDomains = try await trackedDomains(from: privateRecords, in: .privateDatabase) |
| 563 | 587 | let sharedTrackedDomains = try await trackedDomains(from: sharedRecords, in: .sharedDatabase) |
| @@ -601,7 +625,7 @@ final class CloudSyncService { | ||
| 601 | 625 | orderKey: Self.absentRemoteOrderKey |
| 602 | 626 | ) |
| 603 | 627 | |
| 604 | return SyncPayload( | |
| 628 | let payload = SyncPayload( | |
| 605 | 629 | trackedDomains: privateTrackedDomains + sharedTrackedDomains, |
| 606 | 630 | workflows: privateWorkflows + sharedWorkflows, |
| 607 | 631 | appSettings: appSettings, |
| @@ -616,6 +640,11 @@ final class CloudSyncService { | ||
| 616 | 640 | ), |
| 617 | 641 | tombstones: tombstones |
| 618 | 642 | ) |
| 643 | ||
| 644 | return RemoteSyncState( | |
| 645 | payload: payload, | |
| 646 | changeTokens: privateFetch.changeTokens.merging(sharedFetch.changeTokens) { _, shared in shared } | |
| 647 | ) | |
| 619 | 648 | } |
| 620 | 649 | |
| 621 | 650 | /// Stands in for a singleton record the zone does not hold yet. It has to |
| @@ -864,10 +893,11 @@ final class CloudSyncService { | ||
| 864 | 893 | if let serverDate = pushedServerDates[entry.recordName] ?? remoteServerDates[entry.recordName] { |
| 865 | 894 | authority[entry.recordName] = StoredRowAuthority(serverDate: serverDate, deviceDate: entry.deviceDate) |
| 866 | 895 | } else if let carried = previous[entry.recordName], carried.deviceDate == entry.deviceDate { |
| 867 | // A read-only shared row is never pushed, so it can turn up | |
| 868 | // in neither list. Keeping the date already recorded for it is | |
| 869 | // what stops it from looking like a local change this device | |
| 870 | // never pushed. | |
| 896 | // A fetch that resumed from a change token only returns what | |
| 897 | // changed, and a read-only shared row is never pushed, so a row | |
| 898 | // can appear in neither list. Keeping the date already recorded | |
| 899 | // for it is what stops it from looking like a local change this | |
| 900 | // device never pushed. | |
| 871 | 901 | authority[entry.recordName] = carried |
| 872 | 902 | } |
| 873 | 903 | } |
| @@ -983,10 +1013,12 @@ final class CloudSyncService { | ||
| 983 | 1013 | /// on a brand-new zone. The private database holds the user's own records in |
| 984 | 1014 | /// a single custom zone; the shared database exposes one zone per accepted |
| 985 | 1015 | /// share, so every shared zone is fetched. |
| 986 | 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]) { | |
| 987 | 1019 | guard let database = cloudKitDatabase(in: scope) else { |
| 988 | 1020 | if scope == .sharedDatabase { |
| 989 | return [] | |
| 1021 | return ([], [:]) | |
| 990 | 1022 | } |
| 991 | 1023 | throw CloudSyncRuntimeError.missingEntitlement |
| 992 | 1024 | } |
| @@ -1000,31 +1032,48 @@ final class CloudSyncService { | ||
| 1000 | 1032 | zoneIDs = try await database.allRecordZones().map(\.zoneID) |
| 1001 | 1033 | } |
| 1002 | 1034 | |
| 1003 | guard !zoneIDs.isEmpty else { return [] } | |
| 1004 | return try await fetchZoneChanges(in: database, zoneIDs: zoneIDs) | |
| 1035 | guard !zoneIDs.isEmpty else { return ([], [:]) } | |
| 1036 | return try await fetchZoneChanges(in: database, scope: scope, zoneIDs: zoneIDs) | |
| 1005 | 1037 | } |
| 1006 | 1038 | |
| 1007 | private func fetchZoneChanges(in database: CKDatabase, zoneIDs: [CKRecordZone.ID]) async throws -> [CKRecord] { | |
| 1008 | // A nil change token requests every record in the zone. The server may | |
| 1009 | // truncate a large response and set `moreComing`, so keep re-fetching | |
| 1010 | // the still-truncated zones with their latest tokens until all drain. | |
| 1011 | var tokensByZone: [CKRecordZone.ID: CKServerChangeToken?] = [:] | |
| 1039 | /// Fetches what changed in each zone since the token stored for it, and | |
| 1040 | /// returns the tokens the caller should store once the changes are safely | |
| 1041 | /// applied. A zone with no stored token is fetched in full. | |
| 1042 | /// | |
| 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?] = [:] | |
| 1012 | 1055 | for zoneID in zoneIDs { |
| 1013 | tokensByZone[zoneID] = .some(nil) | |
| 1056 | pendingByZone[zoneID] = .some(loadChangeToken(forKey: changeTokenStorageKey(scope: scope, zoneID: zoneID))) | |
| 1014 | 1057 | } |
| 1015 | 1058 | |
| 1016 | 1059 | var records: [CKRecord] = [] |
| 1017 | while !tokensByZone.isEmpty { | |
| 1018 | tokensByZone = try await withCheckedThrowingContinuation { continuation in | |
| 1060 | var tokensByZone: [CKRecordZone.ID: CKServerChangeToken] = [:] | |
| 1061 | var refetchedAfterExpiry: Set<CKRecordZone.ID> = [] | |
| 1062 | ||
| 1063 | while !pendingByZone.isEmpty { | |
| 1064 | let step: ZoneChangesStep = try await withCheckedThrowingContinuation { continuation in | |
| 1019 | 1065 | var moreByZone: [CKRecordZone.ID: CKServerChangeToken?] = [:] |
| 1020 | 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 | |
| 1021 | 1070 | let configuration = CKFetchRecordZoneChangesOperation.ZoneConfiguration() |
| 1022 | 1071 | configuration.previousServerChangeToken = token ?? nil |
| 1023 | 1072 | return configuration |
| 1024 | 1073 | } |
| 1025 | 1074 | |
| 1026 | 1075 | let operation = CKFetchRecordZoneChangesOperation( |
| 1027 | recordZoneIDs: Array(tokensByZone.keys), | |
| 1076 | recordZoneIDs: Array(pendingByZone.keys), | |
| 1028 | 1077 | configurationsByRecordZoneID: configurations |
| 1029 | 1078 | ) |
| 1030 | 1079 | operation.recordWasChangedBlock = { _, result in |
| @@ -1033,23 +1082,73 @@ final class CloudSyncService { | ||
| 1033 | 1082 | } |
| 1034 | 1083 | } |
| 1035 | 1084 | operation.recordZoneFetchResultBlock = { zoneID, result in |
| 1036 | if case .success(let value) = result, value.moreComing { | |
| 1037 | moreByZone[zoneID] = .some(value.serverChangeToken) | |
| 1085 | switch result { | |
| 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 | } | |
| 1038 | 1095 | } |
| 1039 | 1096 | } |
| 1040 | 1097 | operation.fetchRecordZoneChangesResultBlock = { result in |
| 1041 | 1098 | switch result { |
| 1042 | 1099 | case .success: |
| 1043 | continuation.resume(returning: moreByZone) | |
| 1100 | continuation.resume( | |
| 1101 | returning: ZoneChangesStep(pendingByZone: moreByZone, tokensByZone: fetchedByZone, expiredZones: expiredZones) | |
| 1102 | ) | |
| 1044 | 1103 | case .failure(let error): |
| 1045 | 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 | } | |
| 1046 | 1116 | } |
| 1047 | 1117 | } |
| 1048 | 1118 | database.add(operation) |
| 1049 | 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 | } | |
| 1050 | 1129 | } |
| 1051 | 1130 | |
| 1052 | return records | |
| 1131 | let changeTokens = tokensByZone.reduce(into: [String: CKServerChangeToken]()) { partialResult, entry in | |
| 1132 | partialResult[changeTokenStorageKey(scope: scope, zoneID: entry.key)] = entry.value | |
| 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 | } | |
| 1146 | ||
| 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 | } | |
| 1053 | 1152 | } |
| 1054 | 1153 | |
| 1055 | 1154 | /// Decodes the payload blob and pairs it with the record's server-assigned |