diff --git a/Modules/Account/Sources/Account/Account.swift b/Modules/Account/Sources/Account/Account.swift index 1e38902bb..82e83ff94 100644 --- a/Modules/Account/Sources/Account/Account.swift +++ b/Modules/Account/Sources/Account/Account.swift @@ -558,19 +558,8 @@ public enum FetchType { delegate.suspendNetwork() } - public func suspendDatabase() { - #if os(iOS) - database.cancelAndSuspend() - #endif - save() - } - - /// Re-open the SQLite database and allow database calls. - /// Call this *before* calling resume. - public func resumeDatabaseAndDelegate() { - #if os(iOS) - database.resume() - #endif + /// Resume network activity for the delegate after a previous `suspendNetwork()`. + public func resumeDelegate() { delegate.resume(account: self) } diff --git a/Modules/Account/Sources/Account/AccountDelegate.swift b/Modules/Account/Sources/Account/AccountDelegate.swift index e4c7bae79..c40787700 100644 --- a/Modules/Account/Sources/Account/AccountDelegate.swift +++ b/Modules/Account/Sources/Account/AccountDelegate.swift @@ -60,9 +60,6 @@ import Secrets /// Suspend all network activity func suspendNetwork() - /// Suspend the SQLite databases - func suspendDatabase() - - /// Make sure no SQLite databases are open and we are ready to issue network requests. + /// Resume network activity after a previous `suspendNetwork()`. func resume(account: Account) } diff --git a/Modules/Account/Sources/Account/AccountManager.swift b/Modules/Account/Sources/Account/AccountManager.swift index a5f350452..e92da557c 100644 --- a/Modules/Account/Sources/Account/AccountManager.swift +++ b/Modules/Account/Sources/Account/AccountManager.swift @@ -272,16 +272,10 @@ import ActivityLog } } - public func suspendDatabaseAll() { - for account in accounts { - account.suspendDatabase() - } - } - public func resumeAll() { isSuspended = false for account in accounts { - account.resumeDatabaseAndDelegate() + account.resumeDelegate() } for account in accounts { account.resume() diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift index 4637a0818..e8cb2930b 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift @@ -497,12 +497,12 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { SyncStatus(articleID: article.articleID, key: SyncStatus.Key(statusKey), flag: flag) }) - try await syncDatabase.insertStatuses(syncStatuses) + await syncDatabase.insertStatuses(syncStatuses) if !syncStatuses.isEmpty { lastNoChangeSyncDate = nil NotificationCenter.default.post(name: .AccountDidQueueArticleStatuses, object: account) } - if let count = try? await syncDatabase.selectPendingCount(), count > 100 { + if let count = await syncDatabase.selectPendingCount(), count > 100 { try await sendArticleStatus(for: account) } @@ -620,22 +620,16 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { } } - // MARK: - Suspend and Resume (for iOS) + // MARK: - Suspend and Resume func suspendNetwork() { Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") refresher.suspend() } - func suspendDatabase() { - Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") - syncDatabase.suspend() - } - func resume(account: Account) { Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") refresher.resume() - syncDatabase.resume() } } @@ -967,7 +961,7 @@ private extension CloudKitAccountDelegate { SyncStatus(articleID: article.articleID, key: statusKey, flag: flag) }) Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") - try? await syncDatabase.insertStatuses(syncStatuses) + await syncDatabase.insertStatuses(syncStatuses) Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete") } diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZoneDelegate.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZoneDelegate.swift index b3227977e..8c8796aee 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZoneDelegate.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZoneDelegate.swift @@ -54,8 +54,8 @@ final class CloudKitArticlesZoneDelegate: CloudKitZoneDelegate { accumulatedChangedCount += changed.count accumulatedDeletedCount += deleted.count do { - let pendingReadStatusArticleIDs = try await syncDatabase.selectPendingReadStatusArticleIDs() ?? Set() - let pendingStarredStatusArticleIDs = try await syncDatabase.selectPendingStarredStatusArticleIDs() ?? Set() + let pendingReadStatusArticleIDs = await syncDatabase.selectPendingReadStatusArticleIDs() ?? Set() + let pendingStarredStatusArticleIDs = await syncDatabase.selectPendingStarredStatusArticleIDs() ?? Set() await delete(recordKeys: deleted, pendingStarredStatusArticleIDs: pendingStarredStatusArticleIDs) try await update(records: changed, @@ -80,7 +80,7 @@ private extension CloudKitArticlesZoneDelegate { return } - try? await syncDatabase.deleteSelectedForProcessing(deletableArticleIDs) + await syncDatabase.deleteSelectedForProcessing(deletableArticleIDs) try? await account?.delete(articleIDs: deletableArticleIDs) } @@ -141,7 +141,7 @@ private extension CloudKitArticlesZoneDelegate { continue } let syncStatuses = Set(deletes.map { SyncStatus(articleID: $0.articleID, key: .deleted, flag: true) }) - try? await self.syncDatabase.insertStatuses(syncStatuses) + await self.syncDatabase.insertStatuses(syncStatuses) } catch { updateError = error Self.logger.error("CloudKit: Error while storing articles: \(error.localizedDescription)") diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitSendStatusOperation.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitSendStatusOperation.swift index 2f5adb06b..2001b8e38 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitSendStatusOperation.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitSendStatusOperation.swift @@ -78,7 +78,7 @@ final class CloudKitSendStatusOperation: MainThreadOperation, @unchecked Sendabl /// Returns the total number of statuses sent and the subset whose article content was also uploaded. func selectForProcessing() async throws -> SendResult { - guard let syncStatuses = try await syncDatabase.selectForProcessing(limit: blockSize), + guard let syncStatuses = await syncDatabase.selectForProcessing(limit: blockSize), !syncStatuses.isEmpty else { return (0, 0) } @@ -104,7 +104,7 @@ final class CloudKitSendStatusOperation: MainThreadOperation, @unchecked Sendabl do { articles = try await account.fetchArticlesAsync(.articleIDs(Set(articleIDs))) } catch { - try? await syncDatabase.resetSelectedForProcessing(Set(syncStatuses.map({ $0.articleID }))) + await syncDatabase.resetSelectedForProcessing(Set(syncStatuses.map({ $0.articleID }))) Self.logger.error("iCloud: Send article status fetch articles error: \(error.localizedDescription)") throw error } @@ -120,16 +120,16 @@ final class CloudKitSendStatusOperation: MainThreadOperation, @unchecked Sendabl // We somehow have new status records but the articles didn't come back // in the fetch. Clean up those sync records and stop processing. if statusUpdates.isEmpty { - try? await syncDatabase.deleteSelectedForProcessing(Set(articleIDs)) + await syncDatabase.deleteSelectedForProcessing(Set(articleIDs)) return nil } do { let withContent = try await articlesZone.modifyArticles(statusUpdates) - try? await syncDatabase.deleteSelectedForProcessing(Set(statusUpdates.map({ $0.articleID }))) + await syncDatabase.deleteSelectedForProcessing(Set(statusUpdates.map({ $0.articleID }))) return (statusUpdates.count, withContent) } catch { - try? await syncDatabase.resetSelectedForProcessing(Set(syncStatuses.map({ $0.articleID }))) + await syncDatabase.resetSelectedForProcessing(Set(syncStatuses.map({ $0.articleID }))) syncErrorHandler?(error, "Sending article status", #fileID, #function, #line) Self.logger.error("iCloud: Send article status modify articles error: \(error.localizedDescription)") throw error diff --git a/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift b/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift index fc6d8525d..600f14b97 100644 --- a/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift +++ b/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift @@ -116,7 +116,7 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable { do { try await account.logActivity(kind: .sendArticleStatuses) { - guard let syncStatuses = try await syncDatabase.selectForProcessing() else { + guard let syncStatuses = await syncDatabase.selectForProcessing() else { return } @@ -385,11 +385,11 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable { SyncStatus(articleID: article.articleID, key: SyncStatus.Key(statusKey), flag: flag) }) - try await syncDatabase.insertStatuses(syncStatuses) + await syncDatabase.insertStatuses(syncStatuses) if !syncStatuses.isEmpty { NotificationCenter.default.post(name: .AccountDidQueueArticleStatuses, object: account) } - if let count = try? await syncDatabase.selectPendingCount(), count > 100 { + if let count = await syncDatabase.selectPendingCount(), count > 100 { try await sendArticleStatus(for: account) } } @@ -413,25 +413,19 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable { } } - // MARK: Suspend and Resume (for iOS) + // MARK: Suspend and Resume /// Suspend all network activity func suspendNetwork() { caller.suspend() } - /// Suspend the SQLLite databases - func suspendDatabase() { - syncDatabase.suspend() - } - - /// Make sure no SQLite databases are open and we are ready to issue network requests. + /// Resume network activity after a previous `suspendNetwork()`. func resume(account: Account) { if credentials == nil { credentials = try? account.retrieveCredentials(type: .basic) } caller.resume() - syncDatabase.resume() } // MARK: - Notifications @@ -710,11 +704,11 @@ private extension FeedbinAccountDelegate { for articleIDGroup in articleIDGroups { do { try await apiCall(articleIDGroup) - try? await self.syncDatabase.deleteSelectedForProcessing(Set(articleIDGroup.map { String($0) })) + await self.syncDatabase.deleteSelectedForProcessing(Set(articleIDGroup.map { String($0) })) } catch { savedError = error Self.logger.error("Feedbin: Article status sync call failed: \(error.localizedDescription)") - try? await self.syncDatabase.resetSelectedForProcessing(Set(articleIDGroup.map { String($0) })) + await self.syncDatabase.resetSelectedForProcessing(Set(articleIDGroup.map { String($0) })) } } @@ -897,7 +891,7 @@ private extension FeedbinAccountDelegate { } do { - guard let pendingArticleIDs = try? await syncDatabase.selectPendingReadStatusArticleIDs() else { + guard let pendingArticleIDs = await syncDatabase.selectPendingReadStatusArticleIDs() else { return } @@ -925,7 +919,7 @@ private extension FeedbinAccountDelegate { } do { - guard let pendingArticleIDs = try? await syncDatabase.selectPendingStarredStatusArticleIDs() else { + guard let pendingArticleIDs = await syncDatabase.selectPendingStarredStatusArticleIDs() else { return } diff --git a/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift b/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift index 85eadffef..ead2e6950 100644 --- a/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift +++ b/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift @@ -215,7 +215,7 @@ import Secrets do { return try await account.logActivity(kind: .sendArticleStatuses, successMessage: successMessage, durationIsSignificant: durationIsSignificant) { () -> Int in - guard let syncStatuses = try await syncDatabase.selectForProcessing() else { + guard let syncStatuses = await syncDatabase.selectForProcessing() else { return 0 } @@ -236,11 +236,11 @@ import Secrets let articleIDs = Set(pending.map { $0.articleID }) do { try await caller.mark(articleIDs, as: pairing.action) - try? await syncDatabase.deleteSelectedForProcessing(articleIDs) + await syncDatabase.deleteSelectedForProcessing(articleIDs) sentCount += articleIDs.count } catch { Self.logger.error("Feedly: Article status sync call failed: \(error.localizedDescription)") - try? await syncDatabase.resetSelectedForProcessing(articleIDs) + await syncDatabase.resetSelectedForProcessing(articleIDs) savedError = error } } @@ -574,12 +574,12 @@ import Secrets SyncStatus(articleID: article.articleID, key: SyncStatus.Key(statusKey), flag: flag) }) - try await syncDatabase.insertStatuses(syncStatuses) + await syncDatabase.insertStatuses(syncStatuses) if !syncStatuses.isEmpty { lastNoChangeSyncDate = nil NotificationCenter.default.post(name: .AccountDidQueueArticleStatuses, object: account) } - if let count = try? await syncDatabase.selectPendingCount(), count > Self.pendingStatusSendThreshold { + if let count = await syncDatabase.selectPendingCount(), count > Self.pendingStatusSendThreshold { try await sendArticleStatus(for: account) } } @@ -628,19 +628,12 @@ import Secrets caller.suspend() } - /// Suspend the SQLite databases. - func suspendDatabase() { - Self.logger.debug("FeedlyAccountDelegate: suspendDatabase") - syncDatabase.suspend() - } - - /// Open the databases and resume network activity. + /// Resume network activity after a previous `suspendNetwork()`. func resume(account: Account) { Self.logger.debug("FeedlyAccountDelegate: resume") if credentials == nil { credentials = try? account.retrieveCredentials(type: .oauthAccessToken) } - syncDatabase.resume() caller.resume() } @@ -731,7 +724,7 @@ private extension FeedlyAccountDelegate { let resource = FeedlyCategoryResourceID.Global.all(for: userID) let remoteUnreadIDs = try await collectStreamIDs(for: resource, unreadOnly: true) - let pendingArticleIDs = (try await syncDatabase.selectPendingReadStatusArticleIDs()) ?? Set() + let pendingArticleIDs = (await syncDatabase.selectPendingReadStatusArticleIDs()) ?? Set() let adjustedRemoteUnreadIDs = remoteUnreadIDs.subtracting(pendingArticleIDs) let localUnreadIDs = try await account.fetchUnreadArticleIDsAsync() @@ -753,7 +746,7 @@ private extension FeedlyAccountDelegate { let resource = FeedlyTagResourceID.Global.saved(for: userID) let remoteStarredIDs = try await collectStreamIDs(for: resource, unreadOnly: nil) - let pendingArticleIDs = (try await syncDatabase.selectPendingStarredStatusArticleIDs()) ?? Set() + let pendingArticleIDs = (await syncDatabase.selectPendingStarredStatusArticleIDs()) ?? Set() let adjustedRemoteStarredIDs = remoteStarredIDs.subtracting(pendingArticleIDs) let localStarredIDs = try await account.fetchStarredArticleIDsAsync() diff --git a/Modules/Account/Sources/Account/LocalAccount/LocalAccountDelegate.swift b/Modules/Account/Sources/Account/LocalAccount/LocalAccountDelegate.swift index aa2ee1f95..3471dc7c2 100644 --- a/Modules/Account/Sources/Account/LocalAccount/LocalAccountDelegate.swift +++ b/Modules/Account/Sources/Account/LocalAccount/LocalAccountDelegate.swift @@ -155,10 +155,6 @@ import Secrets refresher.suspend() } - @MainActor func suspendDatabase() { - // Nothing to do - } - @MainActor func resume(account: Account) { refresher.resume() } diff --git a/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift b/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift index 9ab5a9219..2ef3ca855 100644 --- a/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift +++ b/Modules/Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift @@ -278,11 +278,11 @@ import os for storyHashGroup in storyHashGroups { do { try await apiCall(Set(storyHashGroup)) - try? await syncDatabase.deleteSelectedForProcessing(Set(storyHashGroup)) + await syncDatabase.deleteSelectedForProcessing(Set(storyHashGroup)) } catch { savedError = error Self.logger.error("NewsBlur: Story status sync call failed: \(error.localizedDescription)") - try? await syncDatabase.resetSelectedForProcessing(Set(storyHashGroup)) + await syncDatabase.resetSelectedForProcessing(Set(storyHashGroup)) } } @@ -297,7 +297,7 @@ import os } do { - guard let pendingStoryHashes = try await syncDatabase.selectPendingReadStatusArticleIDs() else { + guard let pendingStoryHashes = await syncDatabase.selectPendingReadStatusArticleIDs() else { return } @@ -325,7 +325,7 @@ import os } do { - guard let pendingStoryHashes = try await syncDatabase.selectPendingStarredStatusArticleIDs() else { + guard let pendingStoryHashes = await syncDatabase.selectPendingStarredStatusArticleIDs() else { return } diff --git a/Modules/Account/Sources/Account/NewsBlur/NewsBlurAccountDelegate.swift b/Modules/Account/Sources/Account/NewsBlur/NewsBlurAccountDelegate.swift index 8676f3d86..57854e3bb 100644 --- a/Modules/Account/Sources/Account/NewsBlur/NewsBlurAccountDelegate.swift +++ b/Modules/Account/Sources/Account/NewsBlur/NewsBlurAccountDelegate.swift @@ -117,7 +117,7 @@ import Secrets } try await account.logActivity(kind: .sendArticleStatuses) { - guard let syncStatuses = try await syncDatabase.selectForProcessing() else { + guard let syncStatuses = await syncDatabase.selectForProcessing() else { return } @@ -456,11 +456,11 @@ import Secrets SyncStatus(articleID: article.articleID, key: SyncStatus.Key(statusKey), flag: flag) }) - try await syncDatabase.insertStatuses(syncStatuses) + await syncDatabase.insertStatuses(syncStatuses) if !syncStatuses.isEmpty { NotificationCenter.default.post(name: .AccountDidQueueArticleStatuses, object: account) } - if let count = try await syncDatabase.selectPendingCount(), count > 100 { + if let count = await syncDatabase.selectPendingCount(), count > 100 { try await sendArticleStatus(for: account) } } @@ -496,18 +496,12 @@ import Secrets caller.suspend() } - /// Suspend the SQLLite databases - func suspendDatabase() { - syncDatabase.suspend() - } - - /// Make sure no SQLite databases are open and we are ready to issue network requests. + /// Resume network activity after a previous `suspendNetwork()`. func resume(account: Account) { if credentials == nil { credentials = try? account.retrieveCredentials(type: .newsBlurSessionID) } caller.resume() - syncDatabase.resume() } // MARK: - Notifications diff --git a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift index 41220d05e..79772af35 100644 --- a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift +++ b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift @@ -183,7 +183,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate { Self.logger.debug("ReaderAPIAccountDelegate: sendArticleStatus") try await account.logActivity(kind: .sendArticleStatuses) { - let syncStatuses = (try await self.syncDatabase.selectForProcessing()) ?? Set() + let syncStatuses = (await self.syncDatabase.selectForProcessing()) ?? Set() let createUnreadStatuses = syncStatuses.filter { $0.key == SyncStatus.Key.read && $0.flag == false } let deleteUnreadStatuses = syncStatuses.filter { $0.key == SyncStatus.Key.read && $0.flag == true } @@ -510,11 +510,11 @@ final class ReaderAPIAccountDelegate: AccountDelegate { SyncStatus(articleID: article.articleID, key: SyncStatus.Key(statusKey), flag: flag) }) - try await syncDatabase.insertStatuses(syncStatuses) + await syncDatabase.insertStatuses(syncStatuses) if !syncStatuses.isEmpty { NotificationCenter.default.post(name: .AccountDidQueueArticleStatuses, object: account) } - if let count = try await syncDatabase.selectPendingCount(), count > 100 { + if let count = await syncDatabase.selectPendingCount(), count > 100 { try? await sendArticleStatus(for: account) } } @@ -553,19 +553,11 @@ final class ReaderAPIAccountDelegate: AccountDelegate { caller.cancelAll() } - /// Suspend the SQLLite databases - func suspendDatabase() { - Self.logger.debug("ReaderAPIAccountDelegate: suspendDatabase") - - syncDatabase.suspend() - } - - /// Make sure no SQLite databases are open and we are ready to issue network requests. + /// Resume network activity after a previous `suspendNetwork()`. func resume(account: Account) { Self.logger.debug("ReaderAPIAccountDelegate: resume") retrieveCredentialsIfNeeded(account) - syncDatabase.resume() } // MARK: - Notifications @@ -786,10 +778,10 @@ private extension ReaderAPIAccountDelegate { do { _ = try await apiCall(articleIDGroup) - try? await syncDatabase.deleteSelectedForProcessing(Set(articleIDGroup)) + await syncDatabase.deleteSelectedForProcessing(Set(articleIDGroup)) } catch { Self.logger.error("ReaderAPIAccountDelegate: sendArticleStatuses — error \(error.localizedDescription)") - try? await syncDatabase.resetSelectedForProcessing(Set(articleIDGroup)) + await syncDatabase.resetSelectedForProcessing(Set(articleIDGroup)) } } } @@ -949,7 +941,7 @@ private extension ReaderAPIAccountDelegate { Task { @MainActor in do { - let pendingArticleIDs = (try await self.syncDatabase.selectPendingReadStatusArticleIDs()) ?? Set() + let pendingArticleIDs = (await self.syncDatabase.selectPendingReadStatusArticleIDs()) ?? Set() let updatableReaderUnreadArticleIDs = Set(articleIDs).subtracting(pendingArticleIDs) @@ -978,7 +970,7 @@ private extension ReaderAPIAccountDelegate { do { - let pendingArticleIDs = (try await self.syncDatabase.selectPendingStarredStatusArticleIDs()) ?? Set() + let pendingArticleIDs = (await self.syncDatabase.selectPendingStarredStatusArticleIDs()) ?? Set() let updatableReaderUnreadArticleIDs = Set(articleIDs).subtracting(pendingArticleIDs) diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift index 9279ea3fd..249422869 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift @@ -388,32 +388,6 @@ public struct ArticleCounts: Sendable { } } -#if os(iOS) - // MARK: - Suspend and Resume (for iOS) - - /// Cancel current operations and close the database. - @MainActor public func cancelAndSuspend() { - Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") - cancelOperations() - suspend() - } - - /// Close the database and stop running database calls. - /// Any pending calls will complete first. - @MainActor public func suspend() { - Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") - operationQueue.suspend() - queue.suspend() - } - - /// Open the database and allow for running database calls again. - @MainActor public func resume() { - Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") - queue.resume() - operationQueue.resume() - } -#endif - // MARK: - Caches /// Call to free up some memory. Should be done when the app is backgrounded, for instance. @@ -478,19 +452,19 @@ private extension ArticlesDatabase { typealias UnreadCountDictionaryCompletionResult = Result typealias UnreadCountDictionaryCompletionBlock = @Sendable (UnreadCountDictionaryCompletionResult) -> Void -typealias UpdateArticlesResult = Result +typealias UpdateArticlesResult = Result typealias UpdateArticlesCompletionBlock = @Sendable (UpdateArticlesResult) -> Void -typealias SingleUnreadCountResult = Result +typealias SingleUnreadCountResult = Result typealias SingleUnreadCountCompletionBlock = @Sendable (SingleUnreadCountResult) -> Void -typealias ArticleSetResult = Result, DatabaseError> +typealias ArticleSetResult = Result, Error> typealias ArticleSetResultBlock = @Sendable (ArticleSetResult) -> Void typealias ArticleIDsResult = Result, Error> typealias ArticleIDsCompletionBlock = @Sendable (ArticleIDsResult) -> Void -typealias ArticleStatusesResult = Result, DatabaseError> +typealias ArticleStatusesResult = Result, Error> typealias ArticleStatusesResultBlock = @Sendable (ArticleStatusesResult) -> Void private extension ArticlesDatabase { @@ -504,7 +478,7 @@ private extension ArticlesDatabase { } operation.completionBlock = { operation in let fetchOperation = operation as! FetchAllUnreadCountsOperation - completion(fetchOperation.result ?? .failure(DatabaseError.isSuspended)) + completion(fetchOperation.result ?? .success(UnreadCountDictionary())) } operationQueue.add(operation) } diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift index 2da8a9b7f..efbd416dc 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift @@ -110,7 +110,7 @@ final class ArticlesTable: DatabaseTable, Sendable { // MARK: - Fetching Counts Async - func fetchArticleCountsAsync(_ feedIDs: Set, _ completion: @escaping @Sendable (Result) -> Void) { + func fetchArticleCountsAsync(_ feedIDs: Set, _ completion: @escaping @Sendable (Result) -> Void) { queue.runInDatabase { databaseResult in switch databaseResult { case .success(let database): @@ -128,7 +128,7 @@ final class ArticlesTable: DatabaseTable, Sendable { // MARK: - Fetching Last Update Dates - func fetchLastUpdateDatesAsync(_ completion: @escaping @Sendable (Result<[String: Date], DatabaseError>) -> Void) { + func fetchLastUpdateDatesAsync(_ completion: @escaping @Sendable (Result<[String: Date], Error>) -> Void) { queue.runInDatabase { databaseResult in switch databaseResult { case .success(let database): @@ -148,7 +148,7 @@ final class ArticlesTable: DatabaseTable, Sendable { func fetchArticlesMatching(_ searchString: String) throws -> Set
{ nonisolated(unsafe) var articles: Set
= Set
() - nonisolated(unsafe) var error: DatabaseError? + nonisolated(unsafe) var error: Error? queue.runInDatabaseSync { (databaseResult) in switch databaseResult { @@ -429,7 +429,7 @@ final class ArticlesTable: DatabaseTable, Sendable { let parameters = Array(feedIDs) as [Any] guard let resultSet = database.executeQuery(sql, withArgumentsIn: parameters) else { - throw DatabaseError.isSuspended + return UnreadCountDictionary() } defer { resultSet.close() @@ -764,7 +764,7 @@ nonisolated private extension ArticlesTable { private func fetchArticles(_ fetchMethod: @escaping ArticlesFetchMethod) throws -> Set
{ nonisolated(unsafe) var articles = Set
() - nonisolated(unsafe) var error: DatabaseError? + nonisolated(unsafe) var error: Error? queue.runInDatabaseSync { databaseResult in switch databaseResult { @@ -782,7 +782,7 @@ nonisolated private extension ArticlesTable { private func fetchArticlesCount(_ fetchMethod: @escaping ArticlesCountFetchMethod) throws -> Int { nonisolated(unsafe) var articlesCount = 0 - nonisolated(unsafe) var error: DatabaseError? + nonisolated(unsafe) var error: Error? queue.runInDatabaseSync { databaseResult in switch databaseResult { diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchAllUnreadCountsOperation.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchAllUnreadCountsOperation.swift index 4f53d9961..8a2b39c1f 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchAllUnreadCountsOperation.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchAllUnreadCountsOperation.swift @@ -29,13 +29,10 @@ import RSDatabaseObjC switch databaseResult { case .success(let database): - if let unreadCountDictionary = self.fetchUnreadCounts(database) { - self.result = .success(unreadCountDictionary) - } else { - self.result = .failure(DatabaseError.isSuspended) - } - case .failure: - self.result = .failure(DatabaseError.isSuspended) + let unreadCountDictionary = self.fetchUnreadCounts(database) ?? UnreadCountDictionary() + self.result = .success(unreadCountDictionary) + case .failure(let error): + self.result = .failure(error) } self.didComplete() diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift index ee8cb415c..7060603e8 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift @@ -160,7 +160,7 @@ final class StatusesTable: DatabaseTable, Sendable { } func fetchArticleIDs(_ sql: String) throws -> Set { - nonisolated(unsafe) var error: DatabaseError? + nonisolated(unsafe) var error: Error? nonisolated(unsafe) var articleIDs = Set() queue.runInDatabaseSync { databaseResult in switch databaseResult { diff --git a/Modules/RSDatabase/Sources/RSDatabase/Database.swift b/Modules/RSDatabase/Sources/RSDatabase/Database.swift index a8d22a377..b41622c5f 100644 --- a/Modules/RSDatabase/Sources/RSDatabase/Database.swift +++ b/Modules/RSDatabase/Sources/RSDatabase/Database.swift @@ -9,25 +9,14 @@ import Foundation import RSDatabaseObjC -public enum DatabaseError: Error, LocalizedError, Sendable { - case isSuspended // On iOS, to support background refreshing, a database may be suspended. +/// Result type that provides an FMDatabase or an Error. +public typealias DatabaseResult = Result - public var errorDescription: String? { - switch self { - case .isSuspended: - return NSLocalizedString("Database is suspended", comment: "Database suspended error") - } - } -} - -/// Result type that provides an FMDatabase or a DatabaseError. -public typealias DatabaseResult = Result - -/// Block that executes database code or handles DatabaseQueueError. +/// Block that executes database code or handles an Error. public typealias DatabaseBlock = @Sendable (DatabaseResult) -> Void -/// Completion block that provides an optional DatabaseError. -public typealias DatabaseCompletionBlock = @Sendable (DatabaseError?) -> Void +/// Completion block that provides an optional Error. +public typealias DatabaseCompletionBlock = @Sendable (Error?) -> Void /// Dictionary representing one row of database values, keyed by column name. public typealias DatabaseDictionary = [String: Any] @@ -46,7 +35,7 @@ public extension DatabaseResult { } /// Convenience for getting the error from a DatabaseResult. - var error: DatabaseError? { + var error: Error? { switch self { case .success: return nil diff --git a/Modules/RSDatabase/Sources/RSDatabase/DatabaseQueue.swift b/Modules/RSDatabase/Sources/RSDatabase/DatabaseQueue.swift index 18b000e68..a9485a964 100644 --- a/Modules/RSDatabase/Sources/RSDatabase/DatabaseQueue.swift +++ b/Modules/RSDatabase/Sources/RSDatabase/DatabaseQueue.swift @@ -12,13 +12,9 @@ import SQLite3 import RSDatabaseObjC /// Manage a serial queue and a SQLite database. -/// -/// On iOS, the queue can be suspended -/// in order to support background refreshing. public final class DatabaseQueue: Sendable { private struct State: @unchecked Sendable { var isCallingDatabase = false - var isSuspended = false let database: FMDatabase init(_ database: FMDatabase) { @@ -44,56 +40,12 @@ public final class DatabaseQueue: Sendable { self.state.withLock { openDatabase($0.database) } } - // MARK: - Suspend and Resume - - /// Close the SQLite database and don’t allow database calls until resumed. - /// This is for iOS, where we need to close the SQLite database in some conditions. - /// - /// After calling suspend, if you call into the database before calling resume, - /// your code will not run, and runInDatabaseSync and runInTransactionSync will - /// both throw DatabaseQueueError.isSuspended. - /// - /// On Mac, suspend() and resume() are no-ops, since there isn’t a need for them. - public func suspend() { - #if os(iOS) - Self.logger.info("DatabaseQueue: suspending") - state.withLock { state in - guard !state.isSuspended else { - assertionFailure("DatabaseQueue: suspend called when already suspended") - return - } - - state.isSuspended = true - serialDispatchQueue.suspend() - state.database.close() - } - #endif - } - - /// Open the SQLite database. Allow database calls again. - /// iOS only — does nothing on macOS. - public func resume() { - #if os(iOS) - Self.logger.info("DatabaseQueue: resuming") - state.withLock { state in - guard state.isSuspended else { - assertionFailure("DatabaseQueue: resume called when already resumed") - return - } - - state.isSuspended = false - openDatabase(state.database) - serialDispatchQueue.resume() - } - #endif - } - // MARK: - Make Database Calls /// Run a DatabaseBlock synchronously. This call will block the main thread /// potentially for a while, depending on how long it takes to execute /// the DatabaseBlock *and* depending on how many other calls have been - /// scheduled on the queue. Use sparingly — prefer async versions. + /// scheduled on the queue. Use sparingly — prefer async versions. public func runInDatabaseSync(_ databaseBlock: DatabaseBlock) { serialDispatchQueue.sync { self.state.withLock { state in @@ -136,7 +88,7 @@ public final class DatabaseQueue: Sendable { /// Run all the lines that start with "create". /// Use this to create tables, indexes, etc. public func runCreateStatements(_ statements: String) throws { - nonisolated(unsafe) var error: DatabaseError? + nonisolated(unsafe) var error: Error? runInDatabaseSync { result in Self.logger.debug("DatabaseQueue: runCreateStatements") @@ -186,16 +138,12 @@ private extension DatabaseQueue { } autoreleasepool { - if state.isSuspended { - databaseBlock(.failure(.isSuspended)) - } else { - if useTransaction { - state.database.beginTransaction() - } - databaseBlock(.success(state.database)) - if useTransaction { - state.database.commit() - } + if useTransaction { + state.database.beginTransaction() + } + databaseBlock(.success(state.database)) + if useTransaction { + state.database.commit() } } } diff --git a/Modules/SyncDatabase/Sources/SyncDatabase/SyncDatabase.swift b/Modules/SyncDatabase/Sources/SyncDatabase/SyncDatabase.swift index 6fbda14b4..77c30e468 100644 --- a/Modules/SyncDatabase/Sources/SyncDatabase/SyncDatabase.swift +++ b/Modules/SyncDatabase/Sources/SyncDatabase/SyncDatabase.swift @@ -11,7 +11,7 @@ import RSDatabase import RSDatabaseObjC public actor SyncDatabase { - private var database: FMDatabase? + private let database: FMDatabase public nonisolated let databasePath: String public init(databasePath: String) { @@ -26,81 +26,42 @@ public actor SyncDatabase { // MARK: - API public func vacuum() { - database?.vacuum() + database.vacuum() } - public func insertStatuses(_ statuses: Set) throws { - guard let database else { - throw DatabaseError.isSuspended - } + public func insertStatuses(_ statuses: Set) { SyncStatusTable.insertStatuses(statuses, database: database) } - public func selectForProcessing(limit: Int? = nil) throws -> Set? { - guard let database else { - throw DatabaseError.isSuspended - } - return SyncStatusTable.selectForProcessing(limit: limit, database: database) + public func selectForProcessing(limit: Int? = nil) -> Set? { + SyncStatusTable.selectForProcessing(limit: limit, database: database) } - public func selectPendingCount() throws -> Int? { - guard let database else { - throw DatabaseError.isSuspended - } - return SyncStatusTable.selectPendingCount(database: database) + public func selectPendingCount() -> Int? { + SyncStatusTable.selectPendingCount(database: database) } - public func selectPendingReadStatusArticleIDs() throws -> Set? { - guard let database else { - throw DatabaseError.isSuspended - } - return SyncStatusTable.selectPendingReadStatusArticleIDs(database: database) + public func selectPendingReadStatusArticleIDs() -> Set? { + SyncStatusTable.selectPendingReadStatusArticleIDs(database: database) } - public func selectPendingStarredStatusArticleIDs() throws -> Set? { - guard let database else { - throw DatabaseError.isSuspended - } - return SyncStatusTable.selectPendingStarredStatusArticleIDs(database: database) + public func selectPendingStarredStatusArticleIDs() -> Set? { + SyncStatusTable.selectPendingStarredStatusArticleIDs(database: database) } nonisolated public func resetAllSelectedForProcessing() { Task { - try? await _resetAllSelectedForProcessing() + await _resetAllSelectedForProcessing() } } - public func resetSelectedForProcessing(_ articleIDs: Set) throws { - guard let database else { - throw DatabaseError.isSuspended - } + public func resetSelectedForProcessing(_ articleIDs: Set) { SyncStatusTable.resetSelectedForProcessing(articleIDs, database: database) } - public func deleteSelectedForProcessing(_ articleIDs: Set) throws { - guard let database else { - throw DatabaseError.isSuspended - } + public func deleteSelectedForProcessing(_ articleIDs: Set) { SyncStatusTable.deleteSelectedForProcessing(articleIDs, database: database) } - - // MARK: - Suspend and Resume (for iOS) - - nonisolated public func suspend() { -#if os(iOS) - Task { - await _suspend() - } -#endif - } - - nonisolated public func resume() { -#if os(iOS) - Task { - await _resume() - } -#endif - } } // MARK: - Private @@ -111,25 +72,7 @@ private extension SyncDatabase { 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 - } + func _resetAllSelectedForProcessing() { 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 - } } diff --git a/Shared/Timeline/FetchRequestOperation.swift b/Shared/Timeline/FetchRequestOperation.swift index f679cf599..86f73cd94 100644 --- a/Shared/Timeline/FetchRequestOperation.swift +++ b/Shared/Timeline/FetchRequestOperation.swift @@ -223,12 +223,7 @@ private extension FetchRequestOperation { static func postFetchError(_ error: Error, fileName: String = #fileID, functionName: String = #function, lineNumber: Int = #line) { let typeName = String(describing: type(of: error)) - let description: String - if let databaseError = error as? DatabaseError { - description = "\(typeName).\(databaseError): \(error.localizedDescription)" - } else { - description = "\(typeName): \(error.localizedDescription)" - } + let description = "\(typeName): \(error.localizedDescription)" let userInfo = ErrorLogUserInfoKey.userInfo(sourceName: "Timeline", sourceID: errorLogSourceID, operation: "Fetching articles", errorMessage: description, fileName: fileName, functionName: functionName, lineNumber: lineNumber) NotificationCenter.default.post(name: .appDidEncounterError, object: nil, userInfo: userInfo) } diff --git a/iOS/AppDelegate.swift b/iOS/AppDelegate.swift index 6a8e50eb2..0a32ee06b 100644 --- a/iOS/AppDelegate.swift +++ b/iOS/AppDelegate.swift @@ -119,7 +119,7 @@ import Images func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { Task { @MainActor in - self.resumeDatabaseProcessingIfNecessary() + self.resumeIfNecessary() await AccountManager.shared.receiveRemoteNotification(userInfo: userInfo) self.suspendApplication() completionHandler(.newData) @@ -165,7 +165,8 @@ import Images AccountManager.shared.refreshAllWithoutWaiting(errorHandler: errorHandler) } - func resumeDatabaseProcessingIfNecessary() { + /// Un-suspend network activity if it was suspended on background entry. + func resumeIfNecessary() { if AccountManager.shared.isSuspended { AccountManager.shared.resumeAll() Self.logger.info("Application processing resumed.") @@ -358,7 +359,7 @@ private extension AppDelegate { } AccountManager.shared.suspendNetworkAll() - AccountManager.shared.suspendDatabaseAll() + AccountManager.shared.saveAll() ArticleThemeDownloader.shared.cleanUp() AppNotification.postAppDidGoToBackground() @@ -449,7 +450,7 @@ private extension AppDelegate { return } - resumeDatabaseProcessingIfNecessary() + resumeIfNecessary() guard let account = AccountManager.shared.existingAccount(accountID: accountID) else { assertionFailure("Expected account with \(accountID)") diff --git a/iOS/SceneDelegate.swift b/iOS/SceneDelegate.swift index 76de3520a..c66d7cdc2 100644 --- a/iOS/SceneDelegate.swift +++ b/iOS/SceneDelegate.swift @@ -64,13 +64,13 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate { } func windowScene(_ windowScene: UIWindowScene, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { - appDelegate.resumeDatabaseProcessingIfNecessary() + appDelegate.resumeIfNecessary() handleShortcutItem(shortcutItem) completionHandler(true) } func scene(_ scene: UIScene, continue userActivity: NSUserActivity) { - appDelegate.resumeDatabaseProcessingIfNecessary() + appDelegate.resumeIfNecessary() coordinator.handle(userActivity) } @@ -80,7 +80,7 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate { } func sceneWillEnterForeground(_ scene: UIScene) { - appDelegate.resumeDatabaseProcessingIfNecessary() + appDelegate.resumeIfNecessary() appDelegate.prepareAccountsForForeground() coordinator.resetFocus() } @@ -92,7 +92,7 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate { // API func handle(_ response: UNNotificationResponse) { - appDelegate.resumeDatabaseProcessingIfNecessary() + appDelegate.resumeIfNecessary() coordinator.handle(response) }