From 3ee474d7019d97127ae4cb149fbc92aff217aa30 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 6 Jan 2026 09:54:01 -0800 Subject: [PATCH] Add logging to iCloud sync. --- .../CloudKit/CloudKitAccountDelegate.swift | 119 ++++++++++++++++-- .../Sources/CloudKitSync/CloudKitZone.swift | 58 +++++++-- .../CloudKitSync/CloudKitZoneResult.swift | 4 +- 3 files changed, 157 insertions(+), 24 deletions(-) diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift index 6b214f99c..8fad2377c 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift @@ -76,7 +76,7 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { } init(dataFolder: String) { - + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") self.accountZone = CloudKitAccountZone(container: container) self.articlesZone = CloudKitArticlesZone(container: container) @@ -88,12 +88,15 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { NotificationCenter.default.addObserver(self, selector: #selector(refreshProgressDidChange(_:)), name: .progressInfoDidChange, object: refresher) NotificationCenter.default.addObserver(self, selector: #selector(syncProgressDidChange(_:)), name: .progressInfoDidChange, object: syncProgress) + Self.logger.debug("CloutKitAccountDelegate: \(#function, privacy: .public) did complete") } func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable: Any]) async { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") await withCheckedContinuation { continuation in let op = CloudKitRemoteNotificationOperation(accountZone: accountZone, articlesZone: articlesZone, userInfo: userInfo) op.completionBlock = { _ in + Self.logger.debug("CloutKitAccountDelegate: \(#function, privacy: .public) did complete") continuation.resume() } mainThreadOperationQueue.add(op) @@ -111,23 +114,31 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { return } + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") try await standardRefreshAll(for: account) + Self.logger.debug("CloutKitAccountDelegate: \(#function, privacy: .public) did complete") } func syncArticleStatus(for account: Account) async throws { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") try await sendArticleStatus(for: account) try await refreshArticleStatus(for: account) + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete") } func sendArticleStatus(for account: Account) async throws { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") try await sendArticleStatus(account: account, showProgress: false) + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete") } func refreshArticleStatus(for account: Account) async throws { - try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") + return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in let op = CloudKitReceiveStatusOperation(articlesZone: articlesZone) - op.completionBlock = { mainThreadOperaion in - if mainThreadOperaion.isCanceled { + op.completionBlock = { mainThreadOperation in + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete") + if mainThreadOperation.isCanceled { continuation.resume(throwing: CloudKitAccountDelegateError.unknown) } else { continuation.resume(returning: ()) @@ -142,6 +153,7 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { return } + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") let opmlData = try Data(contentsOf: opmlFile) let parserData = ParserData(url: opmlFile.absoluteString, data: opmlData) let opmlDocument = try RSOPMLParser.parseOPML(with: parserData) @@ -153,7 +165,10 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { let normalizedItems = OPMLNormalizer.normalize(opmlItems) syncProgress.addTask() - defer { syncProgress.completeTask() } + defer { + syncProgress.completeTask() + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete") + } do { try await accountZone.importOPML(rootExternalID: rootExternalID, items: normalizedItems) @@ -165,6 +180,10 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { @discardableResult func createFeed(for account: Account, url urlString: String, name: String?, container: Container, validateFeed: Bool) async throws -> Feed { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) url: \(urlString)") + defer { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete url: \(urlString)") + } guard let url = URL(string: urlString) else { throw AccountError.invalidParameter } @@ -174,9 +193,11 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { } func renameFeed(for account: Account, with feed: Feed, to name: String) async throws { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) feed.url: \(feed.url)") let editedName = name.isEmpty ? nil : name syncProgress.addTask() defer { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete feed.url: \(feed.url)") syncProgress.completeTask() } @@ -190,6 +211,11 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { } func removeFeed(account: Account, feed: Feed, container: Container) async throws { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) feed.url: \(feed.url)") + defer { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete feed.url: \(feed.url)") + } + do { try await removeFeedFromCloud(for: account, with: feed, from: container) account.clearFeedMetadata(feed) @@ -207,8 +233,12 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { } func moveFeed(account: Account, feed: Feed, sourceContainer: Container, destinationContainer: Container) async throws { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) feed.url: \(feed.url)") syncProgress.addTask() - defer { syncProgress.completeTask() } + defer { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete feed.url: \(feed.url)") + syncProgress.completeTask() + } do { try await accountZone.moveFeed(feed, from: sourceContainer, to: destinationContainer) @@ -221,8 +251,12 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { } func addFeed(account: Account, feed: Feed, container: Container) async throws { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) feed.url: \(feed.url)") syncProgress.addTask() - defer { syncProgress.completeTask() } + defer { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete feed.url: \(feed.url)") + syncProgress.completeTask() + } do { try await accountZone.addFeed(feed, to: container) @@ -234,12 +268,18 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { } func restoreFeed(for account: Account, feed: Feed, container: any Container) async throws { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) feed.url: \(feed.url)") try await createFeed(for: account, url: feed.url, name: feed.editedName, container: container, validateFeed: true) + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete feed.url: \(feed.url)") } func createFolder(for account: Account, name: String) async throws -> Folder { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) name: \(name)") syncProgress.addTask() - defer { syncProgress.completeTask() } + defer { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete name: \(name)") + syncProgress.completeTask() + } do { let externalID = try await accountZone.createFolder(name: name) @@ -255,6 +295,10 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { } func renameFolder(for account: Account, with folder: Folder, to name: String) async throws { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) new name: \(name)") + defer { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete new name: \(name)") + } syncProgress.addTask() defer { syncProgress.completeTask() } @@ -268,6 +312,10 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { } func removeFolder(for account: Account, with folder: Folder) async throws { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) name: \(folder.name ?? "")") + defer { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete name: \(folder.name ?? "")") + } syncProgress.addTask() let feedExternalIDs: [String] @@ -323,6 +371,10 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { guard let name = folder.name else { throw AccountError.invalidParameter } + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) name: \(name)") + defer { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete name: \(name)") + } let feedsToRestore = folder.topLevelFeeds syncProgress.addTasks(1 + feedsToRestore.count) @@ -359,6 +411,7 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { } func markArticles(for account: Account, articles: Set
, statusKey: ArticleStatus.Key, flag: Bool) async throws { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") let articles = try await account.updateAsync(articles: articles, statusKey: statusKey, flag: flag) let syncStatuses = Set(articles.map { article in SyncStatus(articleID: article.articleID, key: SyncStatus.Key(statusKey), flag: flag) @@ -368,9 +421,11 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { if let count = try? await syncDatabase.selectPendingCount(), count > 100 { try await sendArticleStatus(for: account) } + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete") } func accountDidInitialize(_ account: Account) { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") self.account = account accountZone.delegate = CloudKitAcountZoneDelegate(account: account, articlesZone: articlesZone) @@ -386,7 +441,7 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { account.externalID = externalID try? await self.initialRefreshAll(for: account) } catch { - Self.logger.error("CloudKit: Error adding account container: \(error.localizedDescription)") + Self.logger.error("CloudKitAccountDelegate: \(#function, privacy: .public) error: \(error.localizedDescription)") } } accountZone.subscribeToZoneChanges() @@ -396,8 +451,10 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { } func accountWillBeDeleted(_ account: Account) { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") accountZone.resetChangeToken() articlesZone.resetChangeToken() + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete") } static func validateCredentials(transport: Transport, credentials: Credentials, endpoint: URL?) async throws -> Credentials? { @@ -407,14 +464,17 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { // MARK: - Suspend and Resume (for iOS) func suspendNetwork() { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") refresher.suspend() } func suspendDatabase() { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") syncDatabase.suspend() } func resume() { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") refresher.resume() syncDatabase.resume() } @@ -450,6 +510,11 @@ private extension CloudKitAccountDelegate { } func performRefreshAll(for account: Account, sendArticleStatus: Bool) async throws { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) sendArticleStatus: \(sendArticleStatus ? "true" : "false")") + defer { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete") + } + syncProgress.addTasks(3) do { @@ -477,6 +542,10 @@ private extension CloudKitAccountDelegate { } func createRSSFeed(for account: Account, url: URL, editedName: String?, container: Container, validateFeed: Bool) async throws -> Feed { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) url: \(url)") + defer { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete url: \(url)") + } syncProgress.addTasks(5) do { @@ -516,6 +585,10 @@ private extension CloudKitAccountDelegate { } func createAndSyncFeed(account: Account, feedURL: URL, bestFeedSpecifier: FeedSpecifier, editedName: String?, container: Container) async throws -> Feed { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) feedURL: \(feedURL)") + defer { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete feedURL: \(feedURL)") + } let feed = account.createFeed(with: nil, url: feedURL.absoluteString, feedID: feedURL.absoluteString, homePageURL: nil) feed.editedName = editedName container.addFeedToTreeAtTopLevel(feed) @@ -537,6 +610,7 @@ private extension CloudKitAccountDelegate { } func downloadAndParseFeed(feedURL: URL, feed: Feed) async throws -> ParsedFeed { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) feedURL: \(feedURL)") let (parsedFeed, response) = try await InitialFeedDownloader.download(feedURL) syncProgress.completeTask() feed.lastCheckDate = Date() @@ -551,10 +625,12 @@ private extension CloudKitAccountDelegate { feed.conditionalGetInfo = conditionalGetInfo } + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete") return parsedFeed } func updateAndCreateFeedInCloud(account: Account, feed: Feed, parsedFeed: ParsedFeed, bestFeedSpecifier: FeedSpecifier, editedName: String?, container: Container) async throws { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) feed.url: \(feed.url)") _ = try await account.updateAsync(feed: feed, parsedFeed: parsedFeed) let externalID = try await accountZone.createFeed(url: bestFeedSpecifier.urlString, @@ -565,13 +641,18 @@ private extension CloudKitAccountDelegate { syncProgress.completeTask() feed.externalID = externalID sendNewArticlesToTheCloud(account, feed) + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete") } func addDeadFeed(account: Account, url: URL, editedName: String?, container: Container) async throws -> Feed { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") let feed = account.createFeed(with: editedName, url: url.absoluteString, feedID: url.absoluteString, homePageURL: nil) container.addFeedToTreeAtTopLevel(feed) - defer { syncProgress.completeTask() } + defer { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete") + syncProgress.completeTask() + } do { let externalID = try await accountZone.createFeed(url: url.absoluteString, @@ -583,11 +664,13 @@ private extension CloudKitAccountDelegate { return feed } catch { container.removeFeedFromTreeAtTopLevel(feed) + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) error: \(error.localizedDescription)") throw error } } func sendNewArticlesToTheCloud(_ account: Account, _ feed: Feed) { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") Task { do { let articles = try await account.fetchArticlesAsync(.feed(feed)) @@ -598,22 +681,26 @@ private extension CloudKitAccountDelegate { try await sendArticleStatus(account: account, showProgress: true) try? await articlesZone.fetchChangesInZone() } catch { - Self.logger.error("CloudKit: Feed send articles error: \(error.localizedDescription)") + Self.logger.error("CloudKitAccountDelegate: \(#function, privacy: .public) error: \(error.localizedDescription)") } + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete") } } func processAccountError(_ account: Account, _ error: Error) { if case CloudKitZoneError.userDeletedZone = error { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) \(error)") account.removeFeedsFromTreeAtTopLevel(account.topLevelFeeds) for folder in account.folders ?? Set() { account.removeFolderFromTree(folder) } + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete") } } func storeArticleChanges(new: Set
?, updated: Set
?, deleted: Set
?) async { // New records with a read status aren't really new, they just didn't have the read article stored + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") await withTaskGroup(of: Void.self) { group in if let new = new { let filteredNew = new.filter { $0.status.read == false } @@ -630,6 +717,7 @@ private extension CloudKitAccountDelegate { await self.insertSyncStatuses(articles: deleted, statusKey: .deleted, flag: true) } } + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete") } func insertSyncStatuses(articles: Set
?, statusKey: SyncStatus.Key, flag: Bool) async { @@ -639,15 +727,19 @@ private extension CloudKitAccountDelegate { let syncStatuses = Set(articles.map { article in SyncStatus(articleID: article.articleID, key: statusKey, flag: flag) }) + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") try? await syncDatabase.insertStatuses(syncStatuses) + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete") } func sendArticleStatus(account: Account, showProgress: Bool) async throws { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in let op = CloudKitSendStatusOperation(account: account, articlesZone: articlesZone, database: syncDatabase) op.completionBlock = { mainThreadOperation in + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete") if mainThreadOperation.isCanceled { continuation.resume(throwing: CloudKitAccountDelegateError.unknown) } else { @@ -659,6 +751,11 @@ private extension CloudKitAccountDelegate { } func removeFeedFromCloud(for account: Account, with feed: Feed, from container: Container) async throws { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") + defer { + Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete") + } + syncProgress.addTasks(2) do { diff --git a/Modules/CloudKitSync/Sources/CloudKitSync/CloudKitZone.swift b/Modules/CloudKitSync/Sources/CloudKitSync/CloudKitZone.swift index 8e097b258..c3d204217 100644 --- a/Modules/CloudKitSync/Sources/CloudKitSync/CloudKitZone.swift +++ b/Modules/CloudKitSync/Sources/CloudKitSync/CloudKitZone.swift @@ -103,6 +103,7 @@ public extension CloudKitZone { /// Moves the change token to the new key name. This can eventually be removed. func migrateChangeToken() { + Self.logger.debug("CloudKitZone: migrateChangeToken \(self.zoneID.zoneName, privacy: .public)") if let tokenData = UserDefaults.standard.object(forKey: oldChangeTokenKey) as? Data, let oldChangeToken = try? NSKeyedUnarchiver.unarchivedObject(ofClass: CKServerChangeToken.self, from: tokenData) { changeToken = oldChangeToken @@ -112,6 +113,7 @@ public extension CloudKitZone { /// Reset the change token used to determine what point in time we are doing changes fetches func resetChangeToken() { + Self.logger.debug("CloudKitZone: resetChangeToken \(self.zoneID.zoneName, privacy: .public)") changeToken = nil } @@ -127,6 +129,7 @@ public extension CloudKitZone { } func receiveRemoteNotification(userInfo: [AnyHashable: Any]) async { + Self.logger.debug("CloudKitZone: receiveRemoteNotification \(self.zoneID.zoneName, privacy: .public) userInfo: \(userInfo)") let note = CKRecordZoneNotification(fromRemoteNotificationDictionary: userInfo) guard note?.recordZoneID?.zoneName == zoneID.zoneName else { return @@ -135,12 +138,13 @@ public extension CloudKitZone { do { try await fetchChangesInZone() } catch { - Self.logger.error("CloudKit: \(self.zoneID.zoneName) remote notification fetch error: \(error.localizedDescription)") + Self.logger.error("CloudKitZone: receiveRemoteNotification \(self.zoneID.zoneName, privacy: .public) fetch error: \(error.localizedDescription)") } } /// Creates the zone record func createZoneRecord(completion: @escaping @MainActor (Result) -> Void) { + Self.logger.debug("CloudKitZone: createZoneRecord \(self.zoneID.zoneName, privacy: .public)") guard let database else { Task { @MainActor in completion(.failure(CloudKitZoneError.unknown)) @@ -161,6 +165,7 @@ public extension CloudKitZone { /// Subscribes to zone changes func subscribeToZoneChanges() { + Self.logger.debug("CloudKitZone: subscribeToZoneChanges \(self.zoneID.zoneName, privacy: .public)") let subscription = CKRecordZoneSubscription(zoneID: zoneID, subscriptionID: zoneID.zoneName) let info = CKSubscription.NotificationInfo() @@ -169,13 +174,14 @@ public extension CloudKitZone { save(subscription) { result in if case .failure(let error) = result { - Self.logger.error("CloudKit: \(self.zoneID.zoneName) zone subscribe to changes error: \(error.localizedDescription)") + Self.logger.error("CloudKitZone: subscribeToZoneChanges \(self.zoneID.zoneName, privacy: .public) zone error: \(error.localizedDescription)") } } } /// Issue a CKQuery and return the resulting CKRecords. func query(_ ckQuery: CKQuery, desiredKeys: [String]? = nil, completion: @escaping (Result<[CKRecord], Error>) -> Void) { + Self.logger.debug("CloudKitZone: query ckQuery \(self.zoneID.zoneName, privacy: .public)") var records = [CKRecord]() let op = CKQueryOperation(query: ckQuery) @@ -224,7 +230,7 @@ public extension CloudKitZone { } } case .retry(let timeToWait): - Self.logger.debug("CloudKit: \(self.zoneID.zoneName) zone query retry in \(timeToWait) seconds") + Self.logger.debug("CloudKitZone: \(self.zoneID.zoneName, privacy: .public) zone query retry in \(timeToWait) seconds") self.retryIfPossible(after: timeToWait) { self.query(ckQuery, desiredKeys: desiredKeys, completion: completion) } @@ -245,6 +251,7 @@ public extension CloudKitZone { /// Query CKRecords using a CKQuery Cursor func query(cursor: CKQueryOperation.Cursor, desiredKeys: [String]? = nil, carriedRecords: [CKRecord], completion: @escaping (Result<[CKRecord], Error>) -> Void) { + Self.logger.debug("CloudKitZone: query cursor \(self.zoneID.zoneName, privacy: .public)") var records = carriedRecords let op = CKQueryOperation(cursor: cursor) @@ -293,7 +300,7 @@ public extension CloudKitZone { } } case .retry(let timeToWait): - Self.logger.debug("CloudKit: \(self.zoneID.zoneName) zone query retry in \(timeToWait) seconds") + Self.logger.debug("CloudKitZone: query cursor \(self.zoneID.zoneName, privacy: .public) zone query retry in \(timeToWait) seconds") self.retryIfPossible(after: timeToWait) { self.query(cursor: cursor, desiredKeys: desiredKeys, carriedRecords: records, completion: completion) } @@ -314,6 +321,7 @@ public extension CloudKitZone { /// Fetch a CKRecord by using its externalID func fetch(externalID: String?, completion: @escaping (Result) -> Void) { + Self.logger.debug("CloudKitZone: fetch \(self.zoneID.zoneName, privacy: .public) externalID: \(externalID ?? "")") guard let externalID else { completion(.failure(CloudKitZoneError.corruptAccount)) return @@ -352,7 +360,7 @@ public extension CloudKitZone { } } case .retry(let timeToWait): - Self.logger.debug("CloudKit: \(self.zoneID.zoneName) zone fetch retry in \(timeToWait) seconds") + Self.logger.debug("CloudKitZone: fetch \(self.zoneID.zoneName, privacy: .public) externalID: \(externalID) zone fetch retry in \(timeToWait) seconds") self.retryIfPossible(after: timeToWait) { self.fetch(externalID: externalID, completion: captures.completion) } @@ -371,16 +379,19 @@ public extension CloudKitZone { /// Save the CKRecord func save(_ record: CKRecord, completion: @escaping (Result) -> Void) { + Self.logger.debug("CloudKitZone: save \(self.zoneID.zoneName, privacy: .public)") modify(recordsToSave: [record], recordIDsToDelete: [], completion: completion) } /// Save the CKRecords func save(_ records: [CKRecord], completion: @escaping (Result) -> Void) { + Self.logger.debug("CloudKitZone: save records \(self.zoneID.zoneName, privacy: .public)") modify(recordsToSave: records, recordIDsToDelete: [], completion: completion) } /// Saves or modifies the records as long as they are unchanged relative to the local version func saveIfNew(_ records: [CKRecord], completion: @escaping (Result) -> Void) { + Self.logger.debug("CloudKitZone: saveIfNew \(self.zoneID.zoneName, privacy: .public)") let op = CKModifyRecordsOperation(recordsToSave: records, recordIDsToDelete: [CKRecord.ID]()) op.savePolicy = .ifServerRecordUnchanged op.isAtomic = false @@ -459,6 +470,7 @@ public extension CloudKitZone { /// Save the CKSubscription func save(_ subscription: CKSubscription, completion: @escaping (Result) -> Void) { + Self.logger.debug("CloudKitZone: save subscription \(self.zoneID.zoneName, privacy: .public)") // Wrapper to safely transfer non-Sendable values in @Sendable closure let captures = CloudKitZoneCaptures(zone: self, completion: completion) @@ -486,7 +498,7 @@ public extension CloudKitZone { } } case .retry(let timeToWait): - Self.logger.debug("CloudKit: \(self.zoneID.zoneName) save subscription retry in \(timeToWait) seconds") + Self.logger.debug("CloudKitZone: \(self.zoneID.zoneName, privacy: .public) save subscription retry in \(timeToWait) seconds") self.retryIfPossible(after: timeToWait) { self.save(subscription, completion: captures.completion) } @@ -501,6 +513,7 @@ public extension CloudKitZone { /// Delete CKRecords using a CKQuery func delete(ckQuery: CKQuery, completion: @escaping (Result) -> Void) { + Self.logger.debug("CloudKitZone: delete ckQuery \(self.zoneID.zoneName, privacy: .public)") var records = [CKRecord]() @@ -545,6 +558,7 @@ public extension CloudKitZone { /// Delete CKRecords using a CKQuery func delete(cursor: CKQueryOperation.Cursor, carriedRecords: [CKRecord], completion: @escaping (Result) -> Void) { + Self.logger.debug("CloudKitZone: delete cursor \(self.zoneID.zoneName, privacy: .public)") var records = [CKRecord]() @@ -584,16 +598,19 @@ public extension CloudKitZone { /// Delete a CKRecord using its recordID func delete(recordID: CKRecord.ID, completion: @escaping (Result) -> Void) { + Self.logger.debug("CloudKitZone: delete recordID \(self.zoneID.zoneName, privacy: .public)") modify(recordsToSave: [], recordIDsToDelete: [recordID], completion: completion) } /// Delete CKRecords func delete(recordIDs: [CKRecord.ID], completion: @escaping (Result) -> Void) { + Self.logger.debug("CloudKitZone: delete recordIDs \(self.zoneID.zoneName, privacy: .public)") modify(recordsToSave: [], recordIDsToDelete: recordIDs, completion: completion) } /// Delete a CKRecord using its externalID func delete(externalID: String?, completion: @escaping (Result) -> Void) { + Self.logger.debug("CloudKitZone: delete \(self.zoneID.zoneName, privacy: .public) externalID \(externalID ?? "")") guard let externalID = externalID else { completion(.failure(CloudKitZoneError.corruptAccount)) return @@ -605,6 +622,7 @@ public extension CloudKitZone { /// Delete a CKSubscription func delete(subscriptionID: String, completion: @escaping (Result) -> Void) { + Self.logger.debug("CloudKitZone: delete \(self.zoneID.zoneName, privacy: .public) subscriptionID \(subscriptionID)") // Wrapper to safely transfer non-Sendable values in @Sendable closure let captures = CloudKitZoneCaptures(zone: self, completion: completion) @@ -621,7 +639,7 @@ public extension CloudKitZone { captures.completion(.success(())) } case .retry(let timeToWait): - Self.logger.debug("CloudKit: \(self.zoneID.zoneName) delete subscription retry in \(timeToWait) seconds") + Self.logger.debug("CloudKitZone: \(self.zoneID.zoneName, privacy: .public) delete subscription retry in \(timeToWait) seconds") self.retryIfPossible(after: timeToWait) { self.delete(subscriptionID: subscriptionID, completion: captures.completion) } @@ -636,6 +654,7 @@ public extension CloudKitZone { /// Modify and delete the supplied CKRecords and CKRecord.IDs func modify(recordsToSave: [CKRecord], recordIDsToDelete: [CKRecord.ID], completion: @escaping (Result) -> Void) { + Self.logger.debug("CloudKitZone: modify recordsToSave recordIDsToDelete \(self.zoneID.zoneName, privacy: .public)") guard !(recordsToSave.isEmpty && recordIDsToDelete.isEmpty) else { DispatchQueue.main.async { completion(.success(())) @@ -682,7 +701,7 @@ public extension CloudKitZone { completion(.failure(CloudKitZoneError.userDeletedZone)) } case .retry(let timeToWait): - Self.logger.debug("CloudKit: \(self.zoneID.zoneName) zone modify retry in \(timeToWait) seconds") + Self.logger.debug("CloudKitZone: \(self.zoneID.zoneName, privacy: .public) zone modify retry in \(timeToWait) seconds") self.retryIfPossible(after: timeToWait) { self.modify(recordsToSave: recordsToSave, recordIDsToDelete: recordIDsToDelete, completion: completion) } @@ -696,7 +715,7 @@ public extension CloudKitZone { self.modify(recordsToSave: records, recordIDsToDelete: []) { result in switch result { case .success: - Self.logger.info("CloudKit: Saved \(records.count) chunked records") + Self.logger.info("CloudKitZone: \(self.zoneID.zoneName, privacy: .public) Saved \(records.count) chunked records") saveChunks(completion: completion) case .failure(let error): completion(.failure(error)) @@ -713,7 +732,7 @@ public extension CloudKitZone { self.modify(recordsToSave: [], recordIDsToDelete: records) { result in switch result { case .success: - Self.logger.debug("CloudKit: Deleted \(records.count) chunked records") + Self.logger.debug("CloudKitZone: \(self.zoneID.zoneName, privacy: .public) deleted \(records.count) chunked records") deleteChunks() case .failure(let error): DispatchQueue.main.async { @@ -752,7 +771,7 @@ public extension CloudKitZone { /// Fetch all the changes in the CKZone since the last time we checked func fetchChangesInZone(completion: @escaping (Result) -> Void) { - + Self.logger.debug("CloudKitZone: fetchChangesInZone \(self.zoneID.zoneName, privacy: .public)") var savedChangeToken = changeToken var changedRecords = [CKRecord]() @@ -765,27 +784,35 @@ public extension CloudKitZone { op.qualityOfService = Self.qualityOfService op.recordZoneChangeTokensUpdatedBlock = { _, token, _ in + Self.logger.debug("CloudKitZone: fetchChangesInZone \(self.zoneID.zoneName, privacy: .public) recordZoneChangeTokensUpdatedBlock token: \(token)") savedChangeToken = token } op.recordWasChangedBlock = { _, result in + Self.logger.debug("CloudKitZone: fetchChangesInZone \(self.zoneID.zoneName, privacy: .public) recordWasChangedBlock") if let record = try? result.get() { + Self.logger.debug("CloudKitZone: fetchChangesInZone \(self.zoneID.zoneName, privacy: .public) record created \(record.creationDate ?? Date.distantPast) updated \(record.modificationDate ?? Date.distantPast)") changedRecords.append(record) } } op.recordWithIDWasDeletedBlock = { recordID, recordType in + Self.logger.debug("CloudKitZone: fetchChangesInZone \(self.zoneID.zoneName, privacy: .public) recordWithIDWasDeletedBlock \(recordID)") let recordKey = CloudKitRecordKey(recordType: recordType, recordID: recordID) deletedRecordKeys.append(recordKey) } op.recordZoneFetchResultBlock = { _, result in + Self.logger.debug("CloudKitZone: fetchChangesInZone \(self.zoneID.zoneName, privacy: .public) recordZoneFetchResultBlock") if case .success(let (serverChangeToken, _, _)) = result { + Self.logger.debug("CloudKitZone: fetchChangesInZone \(self.zoneID.zoneName, privacy: .public) serverChangeToken \(serverChangeToken)") savedChangeToken = serverChangeToken } } op.fetchRecordZoneChangesResultBlock = { [weak self] result in + let zoneIDName = self?.zoneID.zoneName ?? "[self deallocated]" + Self.logger.debug("CloudKitZone: fetchChangesInZone \(zoneIDName, privacy: .public) fetchRecordZoneChangesResultBlock") guard let self = self else { completion(.failure(CloudKitZoneError.unknown)) return @@ -793,6 +820,7 @@ public extension CloudKitZone { switch result { case .success: + Self.logger.debug("CloudKitZone: fetchChangesInZone \(self.zoneID.zoneName, privacy: .public) success changedRecords count \(changedRecords.count) deletedRecordKeys count \(deletedRecordKeys.count) changeToken \(savedChangeToken)") Task { @MainActor in do { try await self.delegate?.cloudKitDidModify(changed: changedRecords, deleted: deletedRecordKeys) @@ -803,8 +831,10 @@ public extension CloudKitZone { } } case .failure(let error): + Self.logger.debug("CloudKitZone: fetchChangesInZone \(self.zoneID.zoneName, privacy: .public) failure \(error.localizedDescription)") switch CloudKitZoneResult.resolve(error) { case .success: + Self.logger.debug("CloudKitZone: fetchChangesInZone \(self.zoneID.zoneName, privacy: .public) success changedRecords count \(changedRecords.count) deletedRecordKeys count \(deletedRecordKeys.count) changeToken \(savedChangeToken)") Task { @MainActor in do { try await self.delegate?.cloudKitDidModify(changed: changedRecords, deleted: deletedRecordKeys) @@ -815,6 +845,7 @@ public extension CloudKitZone { } } case .zoneNotFound: + Self.logger.debug("CloudKitZone: fetchChangesInZone \(self.zoneID.zoneName, privacy: .public) failure .zoneNotFound") self.createZoneRecord { result in switch result { case .success: @@ -826,20 +857,23 @@ public extension CloudKitZone { } } case .userDeletedZone: + Self.logger.debug("CloudKitZone: fetchChangesInZone \(self.zoneID.zoneName, privacy: .public) failure .userDeletedZone") DispatchQueue.main.async { completion(.failure(CloudKitZoneError.userDeletedZone)) } case .retry(let timeToWait): - Self.logger.debug("CloudKit: \(self.zoneID.zoneName) zone fetch changeds retry in \(timeToWait) seconds") + Self.logger.debug("CloudKitZone: fetchChangesInZone \(self.zoneID.zoneName, privacy: .public) zone fetch changes retry in \(timeToWait) seconds") self.retryIfPossible(after: timeToWait) { self.fetchChangesInZone(completion: completion) } case .changeTokenExpired: + Self.logger.debug("CloudKitZone: fetchChangesInZone \(self.zoneID.zoneName, privacy: .public) failure .changeTokenExpired") DispatchQueue.main.async { self.changeToken = nil self.fetchChangesInZone(completion: completion) } default: + Self.logger.debug("CloudKitZone: fetchChangesInZone \(self.zoneID.zoneName, privacy: .public) failure default") DispatchQueue.main.async { completion(.failure(CloudKitError(error))) } diff --git a/Modules/CloudKitSync/Sources/CloudKitSync/CloudKitZoneResult.swift b/Modules/CloudKitSync/Sources/CloudKitSync/CloudKitZoneResult.swift index c763b1c70..f3cdaf36a 100644 --- a/Modules/CloudKitSync/Sources/CloudKitSync/CloudKitZoneResult.swift +++ b/Modules/CloudKitSync/Sources/CloudKitSync/CloudKitZoneResult.swift @@ -23,7 +23,9 @@ public enum CloudKitZoneResult { public static func resolve(_ error: Error?) -> CloudKitZoneResult { guard error != nil else { return .success } - guard let ckError = error as? CKError else { + cloudKitLogger.info("CloudKitZoneResult: resolve found error \(error.debugDescription)") + + guard let ckError = error as? CKError else { return .failure(error: error!) }