Commit eed2feb5f7

eed2feb5f76ccc9cf483cb73d94100d41ac8f4e7

parent: 03224363e2

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-24 03:45 UTC

Resume zone fetches from a stored change token

`fetchZoneChanges` always started from a nil `previousServerChangeToken`
and never kept the token it reached, so every launch and every foreground
refetched every record in the zone. The token each zone reaches is now
stored per zone and database scope under `cloudSync.changeToken.*`, and
committed only after the fetched changes are on disk and the push has
gone through, so a failure in either step refetches rather than skips.

`CKError.changeTokenExpired` discards the token and refetches that zone
in full, once per zone per sync.

Layout: unified · split

DomainDig/CloudSyncService.swift +128 −29
@@ -90,6 +90,22 @@ private struct SyncPayload {
9090 var tombstones: [SyncRow<SyncTombstone>]
9191}
9292
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.
95private 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.
103private struct ZoneChangesStep {
104 var pendingByZone: [CKRecordZone.ID: CKServerChangeToken?]
105 var tokensByZone: [CKRecordZone.ID: CKServerChangeToken]
106 var expiredZones: [CKRecordZone.ID]
107}
108
93109/// The server date this device last saw for a record, with the payload date the
94110/// row carried at that moment. A row whose payload date has moved since has a
95111/// local change the server has not seen.
@@ -146,6 +162,7 @@ final class CloudSyncService {
146162 static let tombstones = "cloudSync.tombstones"
147163 static let monitoringLocalActivationConfirmed = "cloudSync.monitoringLocalActivationConfirmed"
148164 static let rowAuthority = "cloudSync.rowAuthority"
165 static let changeTokenPrefix = "cloudSync.changeToken."
149166 }
150167
151168 private init(defaults: UserDefaults = .standard) {
@@ -433,7 +450,7 @@ final class CloudSyncService {
433450 do {
434451 let local = loadLocalPayload()
435452 let remote = try await fetchRemotePayload()
436 let merged = merge(local: local, remote: remote)
453 let merged = merge(local: local, remote: remote.payload)
437454 applyMergedPayload(merged.payload)
438455 let pushedServerDates = try await pushMergedPayload(merged.payload)
439456
@@ -441,7 +458,12 @@ final class CloudSyncService {
441458 // local stores round-trip dates through ISO-8601 and through
442459 // `JSONEncoder`, and the next sync compares against what they read
443460 // 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)
445467
446468 lastSyncDate = Date()
447469 defaults.set(lastSyncDate, forKey: StorageKey.lastSyncDate)
@@ -555,9 +577,11 @@ final class CloudSyncService {
555577 )
556578 }
557579
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
561585
562586 let privateTrackedDomains = try await trackedDomains(from: privateRecords, in: .privateDatabase)
563587 let sharedTrackedDomains = try await trackedDomains(from: sharedRecords, in: .sharedDatabase)
@@ -601,7 +625,7 @@ final class CloudSyncService {
601625 orderKey: Self.absentRemoteOrderKey
602626 )
603627
604 return SyncPayload(
628 let payload = SyncPayload(
605629 trackedDomains: privateTrackedDomains + sharedTrackedDomains,
606630 workflows: privateWorkflows + sharedWorkflows,
607631 appSettings: appSettings,
@@ -616,6 +640,11 @@ final class CloudSyncService {
616640 ),
617641 tombstones: tombstones
618642 )
643
644 return RemoteSyncState(
645 payload: payload,
646 changeTokens: privateFetch.changeTokens.merging(sharedFetch.changeTokens) { _, shared in shared }
647 )
619648 }
620649
621650 /// Stands in for a singleton record the zone does not hold yet. It has to
@@ -864,10 +893,11 @@ final class CloudSyncService {
864893 if let serverDate = pushedServerDates[entry.recordName] ?? remoteServerDates[entry.recordName] {
865894 authority[entry.recordName] = StoredRowAuthority(serverDate: serverDate, deviceDate: entry.deviceDate)
866895 } 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.
871901 authority[entry.recordName] = carried
872902 }
873903 }
@@ -983,10 +1013,12 @@ final class CloudSyncService {
9831013 /// on a brand-new zone. The private database holds the user's own records in
9841014 /// a single custom zone; the shared database exposes one zone per accepted
9851015 /// 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]) {
9871019 guard let database = cloudKitDatabase(in: scope) else {
9881020 if scope == .sharedDatabase {
989 return []
1021 return ([], [:])
9901022 }
9911023 throw CloudSyncRuntimeError.missingEntitlement
9921024 }
@@ -1000,31 +1032,48 @@ final class CloudSyncService {
10001032 zoneIDs = try await database.allRecordZones().map(\.zoneID)
10011033 }
10021034
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)
10051037 }
10061038
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?] = [:]
10121055 for zoneID in zoneIDs {
1013 tokensByZone[zoneID] = .some(nil)
1056 pendingByZone[zoneID] = .some(loadChangeToken(forKey: changeTokenStorageKey(scope: scope, zoneID: zoneID)))
10141057 }
10151058
10161059 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
10191065 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
10211070 let configuration = CKFetchRecordZoneChangesOperation.ZoneConfiguration()
10221071 configuration.previousServerChangeToken = token ?? nil
10231072 return configuration
10241073 }
10251074
10261075 let operation = CKFetchRecordZoneChangesOperation(
1027 recordZoneIDs: Array(tokensByZone.keys),
1076 recordZoneIDs: Array(pendingByZone.keys),
10281077 configurationsByRecordZoneID: configurations
10291078 )
10301079 operation.recordWasChangedBlock = { _, result in
@@ -1033,23 +1082,73 @@ final class CloudSyncService {
10331082 }
10341083 }
10351084 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 }
10381095 }
10391096 }
10401097 operation.fetchRecordZoneChangesResultBlock = { result in
10411098 switch result {
10421099 case .success:
1043 continuation.resume(returning: moreByZone)
1100 continuation.resume(
1101 returning: ZoneChangesStep(pendingByZone: moreByZone, tokensByZone: fetchedByZone, expiredZones: expiredZones)
1102 )
10441103 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 }
10461116 }
10471117 }
10481118 database.add(operation)
10491119 }
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 }
10501129 }
10511130
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 }
10531152 }
10541153
10551154 /// Decodes the payload blob and pairs it with the record's server-assigned