From 8e983b83eefbc2501f2a3f0238d2dfa81c8089f6 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Thu, 6 Nov 2025 12:19:48 -0800 Subject: [PATCH] Update several SyncDatabase call sites. --- Modules/Account/Sources/Account/Account.swift | 61 ++++++++ .../CloudKit/CloudKitAccountDelegate.swift | 28 ++-- .../CloudKitArticlesZoneDelegate.swift | 4 +- .../CloudKitSendStatusOperation.swift | 2 +- .../Feedbin/FeedbinAccountDelegate.swift | 26 ++-- .../Feedly/FeedlyAccountDelegate.swift | 26 ++-- .../FeedlySendArticleStatusesOperation.swift | 4 +- .../NewsBlurAccountDelegate+Internal.swift | 140 +++++++----------- .../NewsBlur/NewsBlurAccountDelegate.swift | 66 ++++----- .../ReaderAPI/ReaderAPIAccountDelegate.swift | 26 ++-- .../Sources/SyncDatabase/SyncDatabase.swift | 42 ++++-- 11 files changed, 238 insertions(+), 187 deletions(-) diff --git a/Modules/Account/Sources/Account/Account.swift b/Modules/Account/Sources/Account/Account.swift index a2579265e..69b3b81a3 100644 --- a/Modules/Account/Sources/Account/Account.swift +++ b/Modules/Account/Sources/Account/Account.swift @@ -702,10 +702,26 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, return try database.fetchStarredArticlesCount(flattenedFeeds().feedIDs()) } + public func fetchUnreadArticleIDs() async throws -> Set { + try await withCheckedThrowingContinuation { continuation in + fetchUnreadArticleIDs { result in + continuation.resume(with: result) + } + } + } + public func fetchUnreadArticleIDs(_ completion: @escaping ArticleIDsCompletionBlock) { database.fetchUnreadArticleIDsAsync(completion: completion) } + public func fetchStarredArticleIDs() async throws -> Set { + try await withCheckedThrowingContinuation { continuation in + fetchStarredArticleIDs { result in + continuation.resume(with: result) + } + } + } + public func fetchStarredArticleIDs(_ completion: @escaping ArticleIDsCompletionBlock) { database.fetchStarredArticleIDsAsync(completion: completion) } @@ -795,6 +811,15 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } } + @discardableResult + func update(_ articles: Set
, statusKey: ArticleStatus.Key, flag: Bool) async throws -> Set
{ + try await withCheckedThrowingContinuation { continuation in + update(articles, statusKey: statusKey, flag: flag) { result in + continuation.resume(with: result) + } + } + } + func update(_ articles: Set
, statusKey: ArticleStatus.Key, flag: Bool, completion: @escaping ArticleSetResultBlock) { // Returns set of Articles whose statuses did change. guard !articles.isEmpty else { @@ -854,24 +879,60 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, /// Mark articleIDs as read. Will create statuses in the database and in memory as needed. Sends a .StatusesDidChange notification. /// Returns a set of new article statuses. + @discardableResult + func markAsRead(_ articleIDs: Set) async throws -> Set { + try await withCheckedThrowingContinuation { continuation in + markAsRead(articleIDs) { result in + continuation.resume(with: result) + } + } + } + func markAsRead(_ articleIDs: Set, completion: ArticleIDsCompletionBlock? = nil) { markAndFetchNew(articleIDs: articleIDs, statusKey: .read, flag: true, completion: completion) } /// Mark articleIDs as unread. Will create statuses in the database and in memory as needed. Sends a .StatusesDidChange notification. /// Returns a set of new article statuses. + @discardableResult + func markAsUnread(_ articleIDs: Set) async throws -> Set { + try await withCheckedThrowingContinuation { continuation in + markAsUnread(articleIDs) { result in + continuation.resume(with: result) + } + } + } + func markAsUnread(_ articleIDs: Set, completion: ArticleIDsCompletionBlock? = nil) { markAndFetchNew(articleIDs: articleIDs, statusKey: .read, flag: false, completion: completion) } /// Mark articleIDs as starred. Will create statuses in the database and in memory as needed. Sends a .StatusesDidChange notification. /// Returns a set of new article statuses. + @discardableResult + func markAsStarred(_ articleIDs: Set) async throws -> Set { + try await withCheckedThrowingContinuation { continuation in + markAsStarred(articleIDs) { result in + continuation.resume(with: result) + } + } + } + func markAsStarred(_ articleIDs: Set, completion: ArticleIDsCompletionBlock? = nil) { markAndFetchNew(articleIDs: articleIDs, statusKey: .starred, flag: true, completion: completion) } /// Mark articleIDs as unstarred. Will create statuses in the database and in memory as needed. Sends a .StatusesDidChange notification. /// Returns a set of new article statuses. + @discardableResult + func markAsUnstarred(_ articleIDs: Set) async throws -> Set { + try await withCheckedThrowingContinuation { continuation in + markAsUnstarred(articleIDs) { result in + continuation.resume(with: result) + } + } + } + func markAsUnstarred(_ articleIDs: Set, completion: ArticleIDsCompletionBlock? = nil) { markAndFetchNew(articleIDs: articleIDs, statusKey: .starred, flag: false, completion: completion) } diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift index cfa87273d..6d2cf5afe 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift @@ -31,7 +31,7 @@ final class CloudKitAccountDelegate: AccountDelegate { private static let logger = cloudKitLogger - private let database: SyncDatabase + private let syncDatabase: SyncDatabase private let container: CKContainer = { let orgID = Bundle.main.object(forInfoDictionaryKey: "OrganizationIdentifier") as! String @@ -63,7 +63,7 @@ final class CloudKitAccountDelegate: AccountDelegate { self.articlesZone = CloudKitArticlesZone(container: container) let databaseFilePath = (dataFolder as NSString).appendingPathComponent("Sync.sqlite3") - self.database = SyncDatabase(databaseFilePath: databaseFilePath) + self.syncDatabase = SyncDatabase(databasePath: databaseFilePath) self.refresher = LocalAccountRefresher() self.refresher.delegate = self @@ -424,12 +424,12 @@ final class CloudKitAccountDelegate: AccountDelegate { account.update(articles, statusKey: statusKey, flag: flag) { result in switch result { case .success(let articles): - let syncStatuses = articles.map { article in + let syncStatuses = Set(articles.map { article in return SyncStatus(articleID: article.articleID, key: SyncStatus.Key(statusKey), flag: flag) - } + }) - self.database.insertStatuses(syncStatuses) { _ in - self.database.selectPendingCount { result in + self.syncDatabase.insertStatuses(syncStatuses) { _ in + self.syncDatabase.selectPendingCount { result in if let count = try? result.get(), count > 100 { self.sendArticleStatus(for: account, showProgress: false) { _ in } } @@ -446,9 +446,9 @@ final class CloudKitAccountDelegate: AccountDelegate { self.account = account accountZone.delegate = CloudKitAcountZoneDelegate(account: account, articlesZone: articlesZone) - articlesZone.delegate = CloudKitArticlesZoneDelegate(account: account, database: database, articlesZone: articlesZone) + articlesZone.delegate = CloudKitArticlesZoneDelegate(account: account, database: syncDatabase, articlesZone: articlesZone) - database.resetAllSelectedForProcessing() + syncDatabase.resetAllSelectedForProcessing() // Check to see if this is a new account and initialize anything we need if account.externalID == nil { @@ -483,12 +483,12 @@ final class CloudKitAccountDelegate: AccountDelegate { } func suspendDatabase() { - database.suspend() + syncDatabase.suspend() } func resume() { refresher.resume() - database.resume() + syncDatabase.resume() } } @@ -779,10 +779,10 @@ private extension CloudKitAccountDelegate { completion() return } - let syncStatuses = articles.map { article in + let syncStatuses = Set(articles.map { article in return SyncStatus(articleID: article.articleID, key: statusKey, flag: flag) - } - database.insertStatuses(syncStatuses) { _ in + }) + syncDatabase.insertStatuses(syncStatuses) { _ in completion() } } @@ -792,7 +792,7 @@ private extension CloudKitAccountDelegate { articlesZone: articlesZone, refreshProgress: refreshProgress, showProgress: showProgress, - database: database) + database: syncDatabase) op.completionBlock = { mainThreadOperaion in if mainThreadOperaion.isCanceled { completion(.failure(CloudKitAccountDelegateError.unknown)) diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZoneDelegate.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZoneDelegate.swift index 0952493ed..6ed86b913 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZoneDelegate.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZoneDelegate.swift @@ -73,7 +73,7 @@ private extension CloudKitArticlesZoneDelegate { return } - database.deleteSelectedForProcessing(Array(deletableArticleIDs)) { _ in + database.deleteSelectedForProcessing(deletableArticleIDs) { _ in self.account?.delete(articleIDs: deletableArticleIDs) { _ in completion() } @@ -146,7 +146,7 @@ private extension CloudKitArticlesZoneDelegate { group.leave() return } - let syncStatuses = deletes.map { SyncStatus(articleID: $0.articleID, key: .deleted, flag: true) } + let syncStatuses = Set(deletes.map { SyncStatus(articleID: $0.articleID, key: .deleted, flag: true) }) self.database.insertStatuses(syncStatuses) { _ in group.leave() } diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitSendStatusOperation.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitSendStatusOperation.swift index 70288dc4d..0a9a02fac 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitSendStatusOperation.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitSendStatusOperation.swift @@ -152,7 +152,7 @@ private extension CloudKitSendStatusOperation { case .success(let articles): processWithArticles(articles) case .failure(let databaseError): - self.database.resetSelectedForProcessing(syncStatuses.map({ $0.articleID })) { _ in + self.database.resetSelectedForProcessing(Set(syncStatuses.map({ $0.articleID }))) { _ in Self.logger.error("iCloud: Send article status fetch articles error: \(databaseError.localizedDescription)") completion(true) } diff --git a/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift b/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift index 1d58ba3e3..17bf0cb27 100644 --- a/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift +++ b/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift @@ -22,7 +22,7 @@ public enum FeedbinAccountDelegateError: String, Error { final class FeedbinAccountDelegate: AccountDelegate { - private let database: SyncDatabase + private let syncDatabase: SyncDatabase private let caller: FeedbinAPICaller private static let logger = Feedbin.logger @@ -48,7 +48,7 @@ final class FeedbinAccountDelegate: AccountDelegate { init(dataFolder: String, transport: Transport?) { let databaseFilePath = (dataFolder as NSString).appendingPathComponent("Sync.sqlite3") - database = SyncDatabase(databaseFilePath: databaseFilePath) + syncDatabase = SyncDatabase(databasePath: databaseFilePath) if transport != nil { @@ -142,7 +142,7 @@ final class FeedbinAccountDelegate: AccountDelegate { Self.logger.info("Feedbin: Sending article statuses") - database.selectForProcessing { result in + syncDatabase.selectForProcessing { result in func processStatuses(_ syncStatuses: [SyncStatus]) { let createUnreadStatuses = syncStatuses.filter { $0.key == SyncStatus.Key.read && $0.flag == false } @@ -566,12 +566,12 @@ final class FeedbinAccountDelegate: AccountDelegate { account.update(articles, statusKey: statusKey, flag: flag) { result in switch result { case .success(let articles): - let syncStatuses = articles.map { article in + let syncStatuses = Set(articles.map { article in return SyncStatus(articleID: article.articleID, key: SyncStatus.Key(statusKey), flag: flag) - } + }) - self.database.insertStatuses(syncStatuses) { _ in - self.database.selectPendingCount { result in + self.syncDatabase.insertStatuses(syncStatuses) { _ in + self.syncDatabase.selectPendingCount { result in if let count = try? result.get(), count > 100 { self.sendArticleStatus(for: account) { _ in } } @@ -606,13 +606,13 @@ final class FeedbinAccountDelegate: AccountDelegate { /// Suspend the SQLLite databases func suspendDatabase() { - database.suspend() + syncDatabase.suspend() } /// Make sure no SQLite databases are open and we are ready to issue network requests. func resume() { caller.resume() - database.resume() + syncDatabase.resume() } } @@ -959,13 +959,13 @@ private extension FeedbinAccountDelegate { apiCall(articleIDGroup) { result in switch result { case .success: - self.database.deleteSelectedForProcessing(articleIDGroup.map { String($0) } ) + self.syncDatabase.deleteSelectedForProcessing(Set(articleIDGroup.map { String($0) } )) group.leave() case .failure(let error): errorOccurred = true Self.logger.error("Feedbin: Article status sync call failed: \(error.localizedDescription)") - self.database.resetSelectedForProcessing(articleIDGroup.map { String($0) } ) + self.syncDatabase.resetSelectedForProcessing(Set(articleIDGroup.map { String($0) } )) group.leave() } } @@ -1275,7 +1275,7 @@ private extension FeedbinAccountDelegate { return } - database.selectPendingReadStatusArticleIDs() { result in + syncDatabase.selectPendingReadStatusArticleIDs() { result in func process(_ pendingArticleIDs: Set) { @@ -1326,7 +1326,7 @@ private extension FeedbinAccountDelegate { return } - database.selectPendingStarredStatusArticleIDs() { result in + syncDatabase.selectPendingStarredStatusArticleIDs() { result in func process(_ pendingArticleIDs: Set) { diff --git a/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift b/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift index 41bc82e3a..c33c20b1d 100644 --- a/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift +++ b/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift @@ -62,7 +62,7 @@ final class FeedlyAccountDelegate: AccountDelegate { internal let caller: FeedlyAPICaller private static let logger = Feedly.logger - private let database: SyncDatabase + private let syncDatabase: SyncDatabase private weak var currentSyncAllOperation: MainThreadOperation? private let operationQueue = MainThreadOperationQueue() @@ -96,7 +96,7 @@ final class FeedlyAccountDelegate: AccountDelegate { } let databaseFilePath = (dataFolder as NSString).appendingPathComponent("Sync.sqlite3") - self.database = SyncDatabase(databaseFilePath: databaseFilePath) + self.syncDatabase = SyncDatabase(databasePath: databaseFilePath) self.oauthAuthorizationClient = api.oauthAuthorizationClient self.caller.delegate = self @@ -137,7 +137,7 @@ final class FeedlyAccountDelegate: AccountDelegate { refreshProgress.reset() - let syncAllOperation = FeedlySyncAllOperation(account: account, feedlyUserId: credentials.username, caller: caller, database: database, lastSuccessfulFetchStartDate: accountMetadata?.lastArticleFetchStartTime, downloadProgress: refreshProgress) + let syncAllOperation = FeedlySyncAllOperation(account: account, feedlyUserId: credentials.username, caller: caller, database: syncDatabase, lastSuccessfulFetchStartDate: accountMetadata?.lastArticleFetchStartTime, downloadProgress: refreshProgress) syncAllOperation.downloadProgress = refreshProgress @@ -178,7 +178,7 @@ final class FeedlyAccountDelegate: AccountDelegate { func sendArticleStatus(for account: Account, completion: @escaping ((Result) -> Void)) { // Ensure remote articles have the same status as they do locally. - let send = FeedlySendArticleStatusesOperation(database: database, service: caller) + let send = FeedlySendArticleStatusesOperation(database: syncDatabase, service: caller) send.completionBlock = { operation in // TODO: not call with success if operation was canceled? Not sure. DispatchQueue.main.async { @@ -201,7 +201,7 @@ final class FeedlyAccountDelegate: AccountDelegate { let group = DispatchGroup() - let ingestUnread = FeedlyIngestUnreadArticleIdsOperation(account: account, userId: credentials.username, service: caller, database: database, newerThan: nil) + let ingestUnread = FeedlyIngestUnreadArticleIdsOperation(account: account, userId: credentials.username, service: caller, database: syncDatabase, newerThan: nil) group.enter() ingestUnread.completionBlock = { _ in @@ -209,7 +209,7 @@ final class FeedlyAccountDelegate: AccountDelegate { } - let ingestStarred = FeedlyIngestStarredArticleIdsOperation(account: account, userId: credentials.username, service: caller, database: database, newerThan: nil) + let ingestStarred = FeedlyIngestStarredArticleIdsOperation(account: account, userId: credentials.username, service: caller, database: syncDatabase, newerThan: nil) group.enter() ingestStarred.completionBlock = { _ in @@ -342,7 +342,7 @@ final class FeedlyAccountDelegate: AccountDelegate { addToCollectionService: caller, syncUnreadIdsService: caller, getStreamContentsService: caller, - database: database, + database: syncDatabase, container: container, progress: refreshProgress) @@ -520,12 +520,12 @@ final class FeedlyAccountDelegate: AccountDelegate { account.update(articles, statusKey: statusKey, flag: flag) { result in switch result { case .success(let articles): - let syncStatuses = articles.map { article in + let syncStatuses = Set(articles.map { article in return SyncStatus(articleID: article.articleID, key: SyncStatus.Key(statusKey), flag: flag) - } + }) - self.database.insertStatuses(syncStatuses) { _ in - self.database.selectPendingCount { result in + self.syncDatabase.insertStatuses(syncStatuses) { _ in + self.syncDatabase.selectPendingCount { result in if let count = try? result.get(), count > 100 { self.sendArticleStatus(for: account) { _ in } } @@ -564,12 +564,12 @@ final class FeedlyAccountDelegate: AccountDelegate { /// Suspend the SQLLite databases func suspendDatabase() { - database.suspend() + syncDatabase.suspend() } /// Make sure no SQLite databases are open and we are ready to issue network requests. func resume() { - database.resume() + syncDatabase.resume() caller.resume() } } diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlySendArticleStatusesOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlySendArticleStatusesOperation.swift index a0b9078d0..3014cfe8c 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlySendArticleStatusesOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlySendArticleStatusesOperation.swift @@ -67,11 +67,11 @@ private extension FeedlySendArticleStatusesOperation { assert(Thread.isMainThread) switch result { case .success: - database.deleteSelectedForProcessing(Array(ids)) { _ in + database.deleteSelectedForProcessing(ids) { _ in group.leave() } case .failure: - database.resetSelectedForProcessing(Array(ids)) { _ in + database.resetSelectedForProcessing(ids) { _ in group.leave() } } diff --git a/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift b/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift index 69b355a36..fb49cf1b6 100644 --- a/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift +++ b/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift @@ -294,15 +294,17 @@ extension NewsBlurAccountDelegate { for storyHashGroup in storyHashGroups { group.enter() apiCall(storyHashGroup) { result in - switch result { - case .success: - self.database.deleteSelectedForProcessing(storyHashGroup.map { String($0) } ) - group.leave() - case .failure(let error): - errorOccurred = true - Self.logger.error("NewsBlur: Story status sync call failed: \(error.localizedDescription)") - self.database.resetSelectedForProcessing(storyHashGroup.map { String($0) } ) - group.leave() + Task { @MainActor in + switch result { + case .success: + try? await self.syncDatabase.deleteSelectedForProcessing(Set(storyHashGroup.map { String($0) } )) + group.leave() + case .failure(let error): + errorOccurred = true + Self.logger.error("NewsBlur: Story status sync call failed: \(error.localizedDescription)") + try? await self.syncDatabase.resetSelectedForProcessing(Set(storyHashGroup.map { String($0) } )) + group.leave() + } } } } @@ -317,96 +319,66 @@ extension NewsBlurAccountDelegate { } func syncStoryReadState(account: Account, hashes: [NewsBlurStoryHash]?, completion: @escaping (() -> Void)) { - guard let hashes = hashes else { - completion() - return - } - - database.selectPendingReadStatusArticleIDs() { result in - func process(_ pendingStoryHashes: Set) { - + Task { @MainActor in + defer { + completion() + } + + guard let hashes else { + return + } + + do { + guard let pendingStoryHashes = try await syncDatabase.selectPendingReadStatusArticleIDs() else { + return + } + let newsBlurUnreadStoryHashes = Set(hashes.map { $0.hash } ) let updatableNewsBlurUnreadStoryHashes = newsBlurUnreadStoryHashes.subtracting(pendingStoryHashes) - - account.fetchUnreadArticleIDs { articleIDsResult in - guard let currentUnreadArticleIDs = try? articleIDsResult.get() else { - return - } - - let group = DispatchGroup() - - // Mark articles as unread - let deltaUnreadArticleIDs = updatableNewsBlurUnreadStoryHashes.subtracting(currentUnreadArticleIDs) - group.enter() - account.markAsUnread(deltaUnreadArticleIDs) { _ in - group.leave() - } - - // Mark articles as read - let deltaReadArticleIDs = currentUnreadArticleIDs.subtracting(updatableNewsBlurUnreadStoryHashes) - group.enter() - account.markAsRead(deltaReadArticleIDs) { _ in - group.leave() - } - - group.notify(queue: DispatchQueue.main) { - completion() - } - } - } - - switch result { - case .success(let pendingArticleIDs): - process(pendingArticleIDs) - case .failure(let error): + + let currentUnreadArticleIDs = try await account.fetchUnreadArticleIDs() + + // Mark articles as unread + let deltaUnreadArticleIDs = updatableNewsBlurUnreadStoryHashes.subtracting(currentUnreadArticleIDs) + try await account.markAsUnread(deltaUnreadArticleIDs) + + // Mark articles as read + let deltaReadArticleIDs = currentUnreadArticleIDs.subtracting(updatableNewsBlurUnreadStoryHashes) + try await account.markAsRead(deltaReadArticleIDs) + } catch { Self.logger.error("NewsBlur: Sync Story Read Status failed: \(error.localizedDescription)") } } } func syncStoryStarredState(account: Account, hashes: [NewsBlurStoryHash]?, completion: @escaping (() -> Void)) { - guard let hashes = hashes else { - completion() - return - } + Task { @MainActor in + defer { + completion() + } - database.selectPendingStarredStatusArticleIDs() { result in - func process(_ pendingStoryHashes: Set) { + guard let hashes else { + return + } + + do { + guard let pendingStoryHashes = try await syncDatabase.selectPendingStarredStatusArticleIDs() else { + return + } let newsBlurStarredStoryHashes = Set(hashes.map { $0.hash } ) let updatableNewsBlurUnreadStoryHashes = newsBlurStarredStoryHashes.subtracting(pendingStoryHashes) - account.fetchStarredArticleIDs { articleIDsResult in - guard let currentStarredArticleIDs = try? articleIDsResult.get() else { - return - } + let currentStarredArticleIDs = try await account.fetchStarredArticleIDs() - let group = DispatchGroup() + // Mark articles as starred + let deltaStarredArticleIDs = updatableNewsBlurUnreadStoryHashes.subtracting(currentStarredArticleIDs) + try await account.markAsStarred(deltaStarredArticleIDs) - // Mark articles as starred - let deltaStarredArticleIDs = updatableNewsBlurUnreadStoryHashes.subtracting(currentStarredArticleIDs) - group.enter() - account.markAsStarred(deltaStarredArticleIDs) { _ in - group.leave() - } - - // Mark articles as unstarred - let deltaUnstarredArticleIDs = currentStarredArticleIDs.subtracting(updatableNewsBlurUnreadStoryHashes) - group.enter() - account.markAsUnstarred(deltaUnstarredArticleIDs) { _ in - group.leave() - } - - group.notify(queue: DispatchQueue.main) { - completion() - } - } - } - - switch result { - case .success(let pendingArticleIDs): - process(pendingArticleIDs) - case .failure(let error): + // Mark articles as unstarred + let deltaUnstarredArticleIDs = currentStarredArticleIDs.subtracting(updatableNewsBlurUnreadStoryHashes) + try await account.markAsUnstarred(deltaUnstarredArticleIDs) + } catch { Self.logger.error("NewsBlur: Sync Story Starred Status failed: \(error.localizedDescription)") } } diff --git a/Modules/Account/Sources/Account/NewsBlur/NewsBlurAccountDelegate.swift b/Modules/Account/Sources/Account/NewsBlur/NewsBlurAccountDelegate.swift index 6e9f2fa5c..a51b958d3 100644 --- a/Modules/Account/Sources/Account/NewsBlur/NewsBlurAccountDelegate.swift +++ b/Modules/Account/Sources/Account/NewsBlur/NewsBlurAccountDelegate.swift @@ -30,7 +30,7 @@ final class NewsBlurAccountDelegate: AccountDelegate { var refreshProgress = DownloadProgress(numberOfTasks: 0) let caller: NewsBlurAPICaller - let database: SyncDatabase + let syncDatabase: SyncDatabase static let logger = NewsBlur.logger @@ -55,7 +55,7 @@ final class NewsBlurAccountDelegate: AccountDelegate { caller = NewsBlurAPICaller(transport: session) } - database = SyncDatabase(databaseFilePath: dataFolder.appending("/DB.sqlite3")) + syncDatabase = SyncDatabase(databasePath: dataFolder.appending("/DB.sqlite3")) } func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable : Any]) async { @@ -143,23 +143,27 @@ final class NewsBlurAccountDelegate: AccountDelegate { } func sendArticleStatus(for account: Account, completion: @escaping (Result) -> ()) { - Self.logger.info("NewsBlur: Sending story statuses") + Task { @MainActor in + Self.logger.info("NewsBlur: Sending story statuses") - database.selectForProcessing { result in + do { + guard let syncStatuses = try await syncDatabase.selectForProcessing() else { + completion(.success(())) + return + } - func processStatuses(_ syncStatuses: [SyncStatus]) { - let createUnreadStatuses = syncStatuses.filter { + let createUnreadStatuses = Array(syncStatuses.filter { $0.key == SyncStatus.Key.read && $0.flag == false - } - let deleteUnreadStatuses = syncStatuses.filter { + }) + let deleteUnreadStatuses = Array(syncStatuses.filter { $0.key == SyncStatus.Key.read && $0.flag == true - } - let createStarredStatuses = syncStatuses.filter { + }) + let createStarredStatuses = Array(syncStatuses.filter { $0.key == SyncStatus.Key.starred && $0.flag == true - } - let deleteStarredStatuses = syncStatuses.filter { + }) + let deleteStarredStatuses = Array(syncStatuses.filter { $0.key == SyncStatus.Key.starred && $0.flag == false - } + }) let group = DispatchGroup() var errorOccurred = false @@ -204,13 +208,8 @@ final class NewsBlurAccountDelegate: AccountDelegate { completion(.success(())) } } - } - - switch result { - case .success(let syncStatuses): - processStatuses(syncStatuses) - case .failure(let databaseError): - completion(.failure(databaseError)) + } catch { + completion(.failure(error)) } } } @@ -592,22 +591,19 @@ final class NewsBlurAccountDelegate: AccountDelegate { } func markArticles(for account: Account, articles: Set
, statusKey: ArticleStatus.Key, flag: Bool, completion: @escaping (Result) -> Void) { - account.update(articles, statusKey: statusKey, flag: flag) { result in - switch result { - case .success(let articles): - let syncStatuses = articles.map { article in + Task { @MainActor in + do { + try await account.update(articles, statusKey: statusKey, flag: flag) + let syncStatuses = Set(articles.map { article in return SyncStatus(articleID: article.articleID, key: SyncStatus.Key(statusKey), flag: flag) - } + }) - self.database.insertStatuses(syncStatuses) { _ in - self.database.selectPendingCount { result in - if let count = try? result.get(), count > 100 { - self.sendArticleStatus(for: account) { _ in } - } - completion(.success(())) - } + try await syncDatabase.insertStatuses(syncStatuses) + if let count = try await syncDatabase.selectPendingCount(), count > 100 { + sendArticleStatus(for: account) { _ in } } - case .failure(let error): + completion(.success(())) + } catch { completion(.failure(error)) } } @@ -636,12 +632,12 @@ final class NewsBlurAccountDelegate: AccountDelegate { /// Suspend the SQLLite databases func suspendDatabase() { - database.suspend() + syncDatabase.suspend() } /// Make sure no SQLite databases are open and we are ready to issue network requests. func resume() { caller.resume() - database.resume() + syncDatabase.resume() } } diff --git a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift index 5ea39b6f1..5c18f0618 100644 --- a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift +++ b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift @@ -38,7 +38,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate { private let variant: ReaderAPIVariant - private let database: SyncDatabase + private let syncDatabase: SyncDatabase private let caller: ReaderAPICaller private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "ReaderAPI") @@ -75,7 +75,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate { init(dataFolder: String, transport: Transport?, variant: ReaderAPIVariant) { let databaseFilePath = (dataFolder as NSString).appendingPathComponent("Sync.sqlite3") - database = SyncDatabase(databaseFilePath: databaseFilePath) + syncDatabase = SyncDatabase(databasePath: databaseFilePath) if transport != nil { caller = ReaderAPICaller(transport: transport!) @@ -208,7 +208,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate { func sendArticleStatus(for account: Account, completion: @escaping ((Result) -> Void)) { Self.logger.info("ReaderAPI: Sending article statuses") - database.selectForProcessing { result in + syncDatabase.selectForProcessing { result in func processStatuses(_ syncStatuses: [SyncStatus]) { let createUnreadStatuses = syncStatuses.filter { $0.key == SyncStatus.Key.read && $0.flag == false } @@ -614,12 +614,12 @@ final class ReaderAPIAccountDelegate: AccountDelegate { account.update(articles, statusKey: statusKey, flag: flag) { result in switch result { case .success(let articles): - let syncStatuses = articles.map { article in + let syncStatuses = Set(articles.map { article in return SyncStatus(articleID: article.articleID, key: SyncStatus.Key(statusKey), flag: flag) - } + }) - self.database.insertStatuses(syncStatuses) { _ in - self.database.selectPendingCount { result in + self.syncDatabase.insertStatuses(syncStatuses) { _ in + self.syncDatabase.selectPendingCount { result in if let count = try? result.get(), count > 100 { self.sendArticleStatus(for: account) { _ in } } @@ -658,12 +658,12 @@ final class ReaderAPIAccountDelegate: AccountDelegate { /// Suspend the SQLLite databases func suspendDatabase() { - database.suspend() + syncDatabase.suspend() } /// Make sure no SQLite databases are open and we are ready to issue network requests. func resume() { - database.resume() + syncDatabase.resume() } } @@ -882,11 +882,11 @@ private extension ReaderAPIAccountDelegate { apiCall(articleIDGroup) { result in switch result { case .success: - self.database.deleteSelectedForProcessing(articleIDGroup.map { $0 } ) + self.syncDatabase.deleteSelectedForProcessing(Set(articleIDGroup.map { $0 } )) group.leave() case .failure(let error): Self.logger.error("ReaderAPI: Article status sync call failed: \(error.localizedDescription)") - self.database.resetSelectedForProcessing(articleIDGroup.map { $0 } ) + self.syncDatabase.resetSelectedForProcessing(Set(articleIDGroup.map { $0 } )) group.leave() } } @@ -1084,7 +1084,7 @@ private extension ReaderAPIAccountDelegate { return } - database.selectPendingReadStatusArticleIDs() { result in + syncDatabase.selectPendingReadStatusArticleIDs() { result in func process(_ pendingArticleIDs: Set) { let updatableReaderUnreadArticleIDs = Set(articleIDs).subtracting(pendingArticleIDs) @@ -1131,7 +1131,7 @@ private extension ReaderAPIAccountDelegate { return } - database.selectPendingStarredStatusArticleIDs() { result in + syncDatabase.selectPendingStarredStatusArticleIDs() { result in func process(_ pendingArticleIDs: Set) { let updatableReaderUnreadArticleIDs = Set(articleIDs).subtracting(pendingArticleIDs) diff --git a/Modules/SyncDatabase/Sources/SyncDatabase/SyncDatabase.swift b/Modules/SyncDatabase/Sources/SyncDatabase/SyncDatabase.swift index e0397776f..db67953bf 100644 --- a/Modules/SyncDatabase/Sources/SyncDatabase/SyncDatabase.swift +++ b/Modules/SyncDatabase/Sources/SyncDatabase/SyncDatabase.swift @@ -60,11 +60,10 @@ public actor SyncDatabase { return SyncStatusTable.selectPendingStarredStatusArticleIDs(database: database) } - public func resetAllSelectedForProcessing() throws { - guard let database else { - throw DatabaseError.isSuspended + nonisolated public func resetAllSelectedForProcessing() { + Task { + try? await _resetAllSelectedForProcessing() } - SyncStatusTable.resetAllSelectedForProcessing(database: database) } public func resetSelectedForProcessing(_ articleIDs: Set) throws { @@ -83,17 +82,18 @@ public actor SyncDatabase { // MARK: - Suspend and Resume (for iOS) - public func suspend() { + nonisolated public func suspend() { #if os(iOS) - database?.close() - database = nil + Task { + _suspend() + } #endif } - public func resume() { + nonisolated public func resume() { #if os(iOS) - if database == nil { - self.database = FMDatabase.openAndSetUpDatabase(path: databasePath) + Task { + _resume() } #endif } @@ -106,4 +106,26 @@ private extension SyncDatabase { static let tableCreationStatements = """ CREATE TABLE if not EXISTS syncStatus (articleID TEXT NOT NULL, key TEXT NOT NULL, flag BOOL NOT NULL DEFAULT 0, selected BOOL NOT NULL DEFAULT 0, PRIMARY KEY (articleID, key)); """ + + func _resetAllSelectedForProcessing() throws { + guard let database else { + throw DatabaseError.isSuspended + } + SyncStatusTable.resetAllSelectedForProcessing(database: database) + } + + func _suspend() { +#if os(iOS) + database?.close() + database = nil +#endif + } + + func _resume() { +#if os(iOS) + if database == nil { + self.database = FMDatabase.openAndSetUpDatabase(path: databasePath) + } +#endif + } }