From d8fccc8f1b6d840cd35f6b9f6be175fc660336db Mon Sep 17 00:00:00 2001 From: Shadowfacts Date: Sat, 8 Jun 2024 12:23:12 -0700 Subject: [PATCH] Purge old persistent history after processing Closes #480 --- .../MastodonCachePersistentStore.swift | 31 ++++++++++++++++--- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/Tusker/CoreData/MastodonCachePersistentStore.swift b/Tusker/CoreData/MastodonCachePersistentStore.swift index a062a1933b..b055d11980 100644 --- a/Tusker/CoreData/MastodonCachePersistentStore.swift +++ b/Tusker/CoreData/MastodonCachePersistentStore.swift @@ -530,11 +530,34 @@ class MastodonCachePersistentStore: NSPersistentCloudKitContainer { defer { PersistentHistoryTokenStore.setToken(token, for: accountInfo) } - let req = NSPersistentHistoryChangeRequest.fetchHistory(after: lastToken) - if let result = try? self.remoteChangesBackgroundContext.execute(req) as? NSPersistentHistoryResult, - let transactions = result.result as? [NSPersistentHistoryTransaction], - !transactions.isEmpty { + let transactions: [NSPersistentHistoryTransaction] + do { + let req = NSPersistentHistoryChangeRequest.fetchHistory(after: lastToken) + if let result = try self.remoteChangesBackgroundContext.execute(req) as? NSPersistentHistoryResult { + transactions = result.result as? [NSPersistentHistoryTransaction] ?? [] + } else { + logger.error("Unexpectedly non-NSPersistentHistoryResult") + return + } + } catch { + logger.error("Unable to fetch persistent history results: \(String(describing: error), privacy: .public)") + return + } + if !transactions.isEmpty { self.processPersistentHistoryTransactions(transactions) + + do { + // delete history only before the last token, because we don't want to invalidate + // the most recent token + let deleteReq = NSPersistentHistoryChangeRequest.deleteHistory(before: lastToken) + let result = try self.remoteChangesBackgroundContext.execute(deleteReq) + if let result = result as? NSPersistentHistoryResult, + result.resultType == .statusOnly { + logger.info("Delete old persistent history result status: \(result.result as! Int)") + } + } catch { + logger.error("Unable to delete old persistent history: \(String(describing: error), privacy: .public)") + } } } }