diff --git a/Modules/Account/Sources/Account/Account.swift b/Modules/Account/Sources/Account/Account.swift index d6bb80088..bbe74f5f2 100644 --- a/Modules/Account/Sources/Account/Account.swift +++ b/Modules/Account/Sources/Account/Account.swift @@ -850,12 +850,14 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, precondition(type == .onMyMac || type == .cloudKit) database.update(with: parsedItems, feedID: feedID, deleteOlder: deleteOlder) { updateArticlesResult in - switch updateArticlesResult { - case .success(let articleChanges): - self.sendNotificationAbout(articleChanges) - completion(.success(articleChanges)) - case .failure(let databaseError): - completion(.failure(databaseError)) + Task { @MainActor in + switch updateArticlesResult { + case .success(let articleChanges): + self.sendNotificationAbout(articleChanges) + completion(.success(articleChanges)) + case .failure(let databaseError): + completion(.failure(databaseError)) + } } } } @@ -882,12 +884,14 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, } database.update(feedIDsAndItems: feedIDsAndItems, defaultRead: defaultRead) { updateArticlesResult in - switch updateArticlesResult { - case .success(let newAndUpdatedArticles): - self.sendNotificationAbout(newAndUpdatedArticles) - completion(nil) - case .failure(let databaseError): - completion(databaseError) + Task { @MainActor in + switch updateArticlesResult { + case .success(let newAndUpdatedArticles): + self.sendNotificationAbout(newAndUpdatedArticles) + completion(nil) + case .failure(let databaseError): + completion(databaseError) + } } } } @@ -908,14 +912,15 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, return } - database.mark(articles, statusKey: statusKey, flag: flag) { result in - switch result { - case .success(let updatedStatuses): + Task { @MainActor in + do { + let updatedStatuses = try await database.mark(articles, statusKey: statusKey, flag: flag) let updatedArticleIDs = updatedStatuses.articleIDs() let updatedArticles = Set(articles.filter{ updatedArticleIDs.contains($0.articleID) }) self.noteStatusesForArticlesDidChange(updatedArticles) + completion(.success(updatedArticles)) - case .failure(let error): + } catch let error as DatabaseError { completion(.failure(error)) } } @@ -924,21 +929,26 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, /// Make sure statuses exist. Any existing statuses won’t be touched. /// All created statuses will be marked as read and not starred. /// Sends a .StatusesDidChange notification. - func createStatusesIfNeeded(articleIDs: Set, completion: DatabaseCompletionBlock? = nil) { - guard !articleIDs.isEmpty else { - completion?(nil) - return - } - database.createStatusesIfNeeded(articleIDs: articleIDs) { error in - if let error = error { - completion?(error) - return - } - self.noteStatusesForArticleIDsDidChange(articleIDs) - completion?(nil) - } + func createStatusesIfNeeded(articleIDs: Set) async throws { + try await database.createStatusesIfNeeded(articleIDs: articleIDs) + noteStatusesForArticleIDsDidChange(articleIDs) } +// func createStatusesIfNeeded(articleIDs: Set, completion: DatabaseCompletionBlock? = nil) { +// guard !articleIDs.isEmpty else { +// completion?(nil) +// return +// } +// database.createStatusesIfNeeded(articleIDs: articleIDs) { error in +// if let error = error { +// completion?(error) +// return +// } +// self.noteStatusesForArticleIDsDidChange(articleIDs) +// completion?(nil) +// } +// } + /// Mark articleIDs statuses based on statusKey and flag. /// Will create statuses in the database and in memory as needed. Sends a .StatusesDidChange notification. /// Returns a set of new article statuses. @@ -947,18 +957,18 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container, completion?(.success(Set())) return } - database.markAndFetchNew(articleIDs: articleIDs, statusKey: statusKey, flag: flag) { result in - switch result { - case .success(let newArticleStatusIDs): + Task { @MainActor in + do { + let newArticleStatusIDs = try await database.markAndFetchNew(articleIDs: articleIDs, statusKey: statusKey, flag: flag) self.noteStatusesForArticleIDsDidChange(articleIDs: articleIDs, statusKey: statusKey, flag: flag) completion?(.success(newArticleStatusIDs)) - case .failure(let databaseError): - completion?(.failure(databaseError)) + } catch { + completion?(.failure(error)) } } } - /// Mark articleIDs as read. Will create statuses in the database and in memory as needed. Sends a .StatusesDidChange notification. + /// 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 { @@ -1250,12 +1260,14 @@ private extension Account { @MainActor func fetchArticlesAsync(feed: Feed, _ completion: @escaping ArticleSetResultBlock) { database.fetchArticlesAsync(feed.feedID) { [weak self] articleSetResult in - switch articleSetResult { - case .success(let articles): - self?.validateUnreadCount(feed, articles) - completion(.success(articles)) - case .failure(let databaseError): - completion(.failure(databaseError)) + Task { @MainActor in + switch articleSetResult { + case .success(let articles): + self?.validateUnreadCount(feed, articles) + completion(.success(articles)) + case .failure(let databaseError): + completion(.failure(databaseError)) + } } } } @@ -1300,12 +1312,14 @@ private extension Account { func fetchArticlesAsync(forContainer container: Container, _ completion: @escaping ArticleSetResultBlock) { let feeds = container.flattenedFeeds() database.fetchArticlesAsync(feeds.feedIDs()) { [weak self] (articleSetResult) in - switch articleSetResult { - case .success(let articles): - self?.validateUnreadCountsAfterFetchingUnreadArticles(feeds, articles) - completion(.success(articles)) - case .failure(let databaseError): - completion(.failure(databaseError)) + Task { @MainActor in + switch articleSetResult { + case .success(let articles): + self?.validateUnreadCountsAfterFetchingUnreadArticles(feeds, articles) + completion(.success(articles)) + case .failure(let databaseError): + completion(.failure(databaseError)) + } } } } @@ -1326,18 +1340,20 @@ private extension Account { func fetchUnreadArticlesAsync(forContainer container: Container, limit: Int?, _ completion: @escaping ArticleSetResultBlock) { let feeds = container.flattenedFeeds() database.fetchUnreadArticlesAsync(feeds.feedIDs(), limit) { [weak self] (articleSetResult) in - switch articleSetResult { - case .success(let articles): + Task { @MainActor in + switch articleSetResult { + case .success(let articles): - // We don't validate limit queries because they, by definition, won't correctly match the - // complete unread state for the given container. - if limit == nil { - self?.validateUnreadCountsAfterFetchingUnreadArticles(feeds, articles) + // We don't validate limit queries because they, by definition, won't correctly match the + // complete unread state for the given container. + if limit == nil { + self?.validateUnreadCountsAfterFetchingUnreadArticles(feeds, articles) + } + + completion(.success(articles)) + case .failure(let databaseError): + completion(.failure(databaseError)) } - - completion(.success(articles)) - case .failure(let databaseError): - completion(.failure(databaseError)) } } } @@ -1470,10 +1486,12 @@ private extension Account { func fetchUnreadCount(_ feed: Feed, _ completion: VoidCompletionBlock?) { Task { @MainActor in database.fetchUnreadCount(feed.feedID) { result in - if let result, let unreadCount = try? result.get() { - feed.unreadCount = unreadCount + Task { @MainActor in + if let result, let unreadCount = try? result.get() { + feed.unreadCount = unreadCount + } + completion?() } - completion?() } } } @@ -1482,10 +1500,12 @@ private extension Account { let feedIDs = Set(feeds.map { $0.feedID }) Task { @MainActor in database.fetchUnreadCounts(for: feedIDs) { result in - if let result, let unreadCountDictionary = try? result.get() { - self.processUnreadCounts(unreadCountDictionary: unreadCountDictionary, feeds: feeds) + Task { @MainActor in + if let result, let unreadCountDictionary = try? result.get() { + self.processUnreadCounts(unreadCountDictionary: unreadCountDictionary, feeds: feeds) + } + completion?() } - completion?() } } } @@ -1493,22 +1513,21 @@ private extension Account { func fetchAllUnreadCounts(_ completion: VoidCompletionBlock? = nil) { fetchingAllUnreadCounts = true Task { @MainActor in - database.fetchAllUnreadCounts { result in - guard let result, let unreadCountDictionary = try? result.get() else { - completion?() - return - } - self.processUnreadCounts(unreadCountDictionary: unreadCountDictionary, feeds: self.flattenedFeeds()) - - self.fetchingAllUnreadCounts = false - self.updateUnreadCount() - - if !self.areUnreadCountsInitialized { - self.areUnreadCountsInitialized = true - self.postUnreadCountDidInitializeNotification() - } + guard let unreadCountDictionary = try? await database.fetchAllUnreadCounts() else { completion?() + return } + + processUnreadCounts(unreadCountDictionary: unreadCountDictionary, feeds: flattenedFeeds()) + fetchingAllUnreadCounts = false + updateUnreadCount() + + if !self.areUnreadCountsInitialized { + self.areUnreadCountsInitialized = true + self.postUnreadCountDidInitializeNotification() + } + + completion?() } } @@ -1555,7 +1574,7 @@ private extension Account { if shouldSendNotification { userInfo[UserInfoKey.feeds] = feeds - NotificationCenter.default.post(name: .AccountDidDownloadArticles, object: self, userInfo: userInfo) + NotificationCenter.default.postOnMainThread(name: .AccountDidDownloadArticles, object: self, userInfo: userInfo) } } } diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitSendStatusOperation.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitSendStatusOperation.swift index 4bf9d6ce6..eda675f6c 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitSendStatusOperation.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitSendStatusOperation.swift @@ -93,10 +93,10 @@ private extension CloudKitSendStatusOperation { } let articleIDs = syncStatuses.map({ $0.articleID }) - account.fetchArticlesAsync(.articleIDs(Set(articleIDs))) { result in + account.fetchArticlesAsync(.articleIDs(Set(articleIDs))) { [syncStatuses] result in func processWithArticles(_ articles: Set
) { - Task { @MainActor in + Task { @MainActor [syncStatuses] in let syncStatusesDict = Dictionary(grouping: syncStatuses, by: { $0.articleID }) let articlesDict = articles.reduce(into: [String: Article]()) { result, article in diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyIngestStarredArticleIdsOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyIngestStarredArticleIdsOperation.swift index 47e797c1f..0cb545ea1 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyIngestStarredArticleIdsOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyIngestStarredArticleIdsOperation.swift @@ -96,13 +96,13 @@ final class FeedlyIngestStarredArticleIdsOperation: FeedlyOperation, @unchecked return } - account.fetchStarredArticleIDs { result in - switch result { - case .success(let localStarredArticleIDs): - self.processStarredArticleIDs(localStarredArticleIDs) - - case .failure(let error): - self.didComplete(with: error) + Task { @MainActor in + do { + let localStarredArticleIDs = try await account.fetchStarredArticleIDs() + processStarredArticleIDs(localStarredArticleIDs) + didComplete() + } catch { + didComplete(with: error) } } } diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyIngestStreamArticleIdsOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyIngestStreamArticleIdsOperation.swift index 32edaed0d..63789fce9 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyIngestStreamArticleIdsOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyIngestStreamArticleIdsOperation.swift @@ -47,25 +47,24 @@ final class FeedlyIngestStreamArticleIdsOperation: FeedlyOperation, @unchecked S return } - switch result { - case .success(let streamIds): - account.createStatusesIfNeeded(articleIDs: Set(streamIds.ids)) { databaseError in + Task { @MainActor in + switch result { + case .success(let streamIds): + do { + try await account.createStatusesIfNeeded(articleIDs: Set(streamIds.ids)) + guard let continuation = streamIds.continuation else { + Feedly.logger.info("Feedly: Reached end of stream for \(self.resource.id)") + didComplete() + return + } - if let error = databaseError { - self.didComplete(with: error) - return + getStreamIds(continuation) + } catch { + didComplete(with: error) } - - guard let continuation = streamIds.continuation else { - Feedly.logger.info("Feedly: Reached end of stream for \(self.resource.id)") - self.didComplete() - return - } - - self.getStreamIds(continuation) + case .failure(let error): + didComplete(with: error) } - case .failure(let error): - didComplete(with: error) } } } diff --git a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyIngestUnreadArticleIdsOperation.swift b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyIngestUnreadArticleIdsOperation.swift index 6b3edbfcc..bbed12efc 100644 --- a/Modules/Account/Sources/Account/Feedly/Operations/FeedlyIngestUnreadArticleIdsOperation.swift +++ b/Modules/Account/Sources/Account/Feedly/Operations/FeedlyIngestUnreadArticleIdsOperation.swift @@ -96,13 +96,12 @@ final class FeedlyIngestUnreadArticleIdsOperation: FeedlyOperation, @unchecked S return } - account.fetchUnreadArticleIDs { result in - switch result { - case .success(let localUnreadArticleIDs): - self.processUnreadArticleIDs(localUnreadArticleIDs) - - case .failure(let error): - self.didComplete(with: error) + Task { @MainActor in + do { + let localUnreadArticleIDs = try await account.fetchUnreadArticleIDs() + processUnreadArticleIDs(localUnreadArticleIDs) + } catch { + didComplete(with: error) } } } diff --git a/Modules/ArticlesDatabase/Package.swift b/Modules/ArticlesDatabase/Package.swift index 3ffa4b6c4..fde57677d 100644 --- a/Modules/ArticlesDatabase/Package.swift +++ b/Modules/ArticlesDatabase/Package.swift @@ -25,7 +25,11 @@ let package = Package( "RSParser", "Articles", ], - swiftSettings: [.swiftLanguageMode(.v5)] + swiftSettings: [ + .enableUpcomingFeature("NonisolatedNonsendingByDefault"), + .enableUpcomingFeature("InferIsolatedConformances"), + .defaultIsolation(MainActor.self) + ] ), ] ) diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift index ea9be5b84..d8f87a80e 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift @@ -20,10 +20,10 @@ import Articles public typealias UnreadCountDictionary = [String: Int] // feedID: unreadCount public typealias UnreadCountDictionaryCompletionResult = Result -public typealias UnreadCountDictionaryCompletionBlock = (UnreadCountDictionaryCompletionResult?) -> Void +public typealias UnreadCountDictionaryCompletionBlock = @Sendable (UnreadCountDictionaryCompletionResult?) -> Void public typealias SingleUnreadCountResult = Result -public typealias SingleUnreadCountCompletionBlock = (SingleUnreadCountResult?) -> Void +public typealias SingleUnreadCountCompletionBlock = @Sendable (SingleUnreadCountResult?) -> Void nonisolated public struct ArticleChanges: Sendable { public let newArticles: Set
? @@ -44,16 +44,16 @@ nonisolated public struct ArticleChanges: Sendable { } public typealias UpdateArticlesResult = Result -public typealias UpdateArticlesCompletionBlock = (UpdateArticlesResult) -> Void +public typealias UpdateArticlesCompletionBlock = @Sendable (UpdateArticlesResult) -> Void public typealias ArticleSetResult = Result, DatabaseError> -public typealias ArticleSetResultBlock = (ArticleSetResult) -> Void +public typealias ArticleSetResultBlock = @Sendable (ArticleSetResult) -> Void -public typealias ArticleIDsResult = Result, DatabaseError> -public typealias ArticleIDsCompletionBlock = (ArticleIDsResult) -> Void +public typealias ArticleIDsResult = Result, Error> +public typealias ArticleIDsCompletionBlock = @Sendable (ArticleIDsResult) -> Void public typealias ArticleStatusesResult = Result, DatabaseError> -public typealias ArticleStatusesResultBlock = (ArticleStatusesResult) -> Void +public typealias ArticleStatusesResultBlock = @Sendable (ArticleStatusesResult) -> Void nonisolated public final class ArticlesDatabase: Sendable { @@ -191,7 +191,22 @@ nonisolated public final class ArticlesDatabase: Sendable { // MARK: - Unread Counts /// Fetch all non-zero unread counts. - @MainActor public func fetchAllUnreadCounts(_ completion: @escaping UnreadCountDictionaryCompletionBlock) { + @MainActor public func fetchAllUnreadCounts() async throws -> UnreadCountDictionary? { + return try await withCheckedThrowingContinuation { continuation in + self.fetchAllUnreadCounts { result in + switch result { + case .success(let unreadCountDictionary): + continuation.resume(returning: unreadCountDictionary) + case .failure(let error): + continuation.resume(throwing: error) + case .none: + continuation.resume(returning: nil) + } + } + } + } + + @MainActor func fetchAllUnreadCounts(_ completion: @escaping UnreadCountDictionaryCompletionBlock) { Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") let operation = FetchAllUnreadCountsOperation(databaseQueue: queue) if let operationName = operation.name { @@ -283,19 +298,47 @@ nonisolated public final class ArticlesDatabase: Sendable { articlesTable.fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDate(completion) } + public func mark(_ articles: Set
, statusKey: ArticleStatus.Key, flag: Bool) async throws -> Set { + try await withCheckedThrowingContinuation { continuation in + self.mark(articles, statusKey: statusKey, flag: flag) { result in + continuation.resume(with: result) + } + } + } + public func mark(_ articles: Set
, statusKey: ArticleStatus.Key, flag: Bool, completion: @escaping ArticleStatusesResultBlock) { Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") return articlesTable.mark(articles, statusKey, flag, completion) } - public func markAndFetchNew(articleIDs: Set, statusKey: ArticleStatus.Key, flag: Bool, completion: @escaping ArticleIDsCompletionBlock) { + public func markAndFetchNew(articleIDs: Set, statusKey: ArticleStatus.Key, flag: Bool) async throws -> Set { + try await withCheckedThrowingContinuation { continuation in + markAndFetchNew(articleIDs: articleIDs, statusKey: statusKey, flag: flag) { result in + continuation.resume(with: result) + } + } + } + + private func markAndFetchNew(articleIDs: Set, statusKey: ArticleStatus.Key, flag: Bool, completion: @escaping ArticleIDsCompletionBlock) { Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") articlesTable.markAndFetchNew(articleIDs, statusKey, flag, completion) } /// Create statuses for specified articleIDs. For existing statuses, don’t do anything. /// For newly-created statuses, mark them as read and not-starred. - public func createStatusesIfNeeded(articleIDs: Set, completion: @escaping DatabaseCompletionBlock) { + public func createStatusesIfNeeded(articleIDs: Set) async throws { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + self.createStatusesIfNeeded(articleIDs: articleIDs) { error in + if let error { + continuation.resume(throwing: error) + } else { + continuation.resume(returning: ()) + } + } + } + } + + func createStatusesIfNeeded(articleIDs: Set, completion: @escaping DatabaseCompletionBlock) { Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") articlesTable.createStatusesIfNeeded(articleIDs, completion) } @@ -354,7 +397,7 @@ nonisolated public final class ArticlesDatabase: Sendable { // MARK: - Private -private extension ArticlesDatabase { +nonisolated private extension ArticlesDatabase { static let tableCreationStatements = """ CREATE TABLE if not EXISTS articles (articleID TEXT NOT NULL PRIMARY KEY, feedID TEXT NOT NULL, uniqueID TEXT NOT NULL, title TEXT, contentHTML TEXT, contentText TEXT, markdown TEXT, url TEXT, externalURL TEXT, summary TEXT, imageURL TEXT, bannerImageURL TEXT, datePublished DATE, dateModified DATE, searchRowID INTEGER); diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift index 67739ee93..70216a431 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift @@ -28,8 +28,8 @@ nonisolated final class ArticlesTable: DatabaseTable, Sendable { // TODO: update articleCutoffDate as time passes and based on user preferences. let articleCutoffDate = Date().bySubtracting(days: 90) - private typealias ArticlesFetchMethod = (FMDatabase) -> Set
- private typealias ArticlesCountFetchMethod = (FMDatabase) -> Int + private typealias ArticlesFetchMethod = @Sendable (FMDatabase) -> Set
+ private typealias ArticlesCountFetchMethod = @Sendable (FMDatabase) -> Int init(name: String, accountID: String, queue: DatabaseQueue, retentionStyle: ArticlesDatabase.RetentionStyle) { self.name = name diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchAllUnreadCountsOperation.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchAllUnreadCountsOperation.swift index a4e87c42e..f055d515c 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchAllUnreadCountsOperation.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchAllUnreadCountsOperation.swift @@ -22,32 +22,30 @@ public final class FetchAllUnreadCountsOperation: MainThreadOperation, @unchecke @MainActor public override func run() { queue.runInDatabase { databaseResult in - Task { @MainActor in - if self.isCanceled { - self.didComplete() - return - } - - switch databaseResult { - case .success(let database): - self.fetchUnreadCounts(database) - case .failure: - self.result = .failure(.isSuspended) - } - + if self.isCanceled { self.didComplete() + return } + + switch databaseResult { + case .success(let database): + self.result = self.fetchUnreadCounts(database) + case .failure: + self.result = .failure(.isSuspended) + } + + self.didComplete() } } } -private extension FetchAllUnreadCountsOperation { +nonisolated private extension FetchAllUnreadCountsOperation { - func fetchUnreadCounts(_ database: FMDatabase) { + func fetchUnreadCounts(_ database: FMDatabase) -> UnreadCountDictionaryCompletionResult? { let sql = "select distinct feedID, count(*) from articles natural join statuses where read=0 group by feedID;" guard let resultSet = database.executeQuery(sql, withArgumentsIn: nil) else { - return + return nil } var unreadCountDictionary = UnreadCountDictionary() @@ -59,6 +57,6 @@ private extension FetchAllUnreadCountsOperation { } resultSet.close() - result = .success(unreadCountDictionary) + return .success(unreadCountDictionary) } } diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchFeedUnreadCountOperation.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchFeedUnreadCountOperation.swift index 520da09ab..c9b22fe0d 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchFeedUnreadCountOperation.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchFeedUnreadCountOperation.swift @@ -29,6 +29,10 @@ public final class FetchFeedUnreadCountOperation: MainThreadOperation, @unchecke @MainActor public override func run() { queue.runInDatabase { databaseResult in + if self.isCanceled { + self.didComplete() + return + } switch databaseResult { case .success(let database): @@ -39,9 +43,7 @@ public final class FetchFeedUnreadCountOperation: MainThreadOperation, @unchecke self.result = .failure(.isSuspended) } - Task { @MainActor in - self.didComplete() - } + self.didComplete() } } } diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchUnreadCountsForFeedsOperation.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchUnreadCountsForFeedsOperation.swift index ff1382304..ce0bcfcd4 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchUnreadCountsForFeedsOperation.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/Operations/FetchUnreadCountsForFeedsOperation.swift @@ -26,6 +26,11 @@ public final class FetchUnreadCountsForFeedsOperation: MainThreadOperation, @unc @MainActor public override func run() { queue.runInDatabase { databaseResult in + if self.isCanceled { + self.didComplete() + return + } + switch databaseResult { case .success(let database): if let unreadCountDictionary = self.fetchUnreadCounts(database) { @@ -34,6 +39,8 @@ public final class FetchUnreadCountsForFeedsOperation: MainThreadOperation, @unc case .failure: self.result = .failure(.isSuspended) } + + self.didComplete() } } } diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/SearchTable.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/SearchTable.swift index 2983179af..f79c3e3e9 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/SearchTable.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/SearchTable.swift @@ -129,7 +129,7 @@ nonisolated final class SearchTable: DatabaseTable, @unchecked Sendable { // MARK: - Private -private extension SearchTable { +nonisolated private extension SearchTable { func performInitialIndexForArticles(_ articles: Set, _ database: FMDatabase) { articles.forEach { performInitialIndex($0, database) } diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift index 095367c49..54589a7fe 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/StatusesTable.swift @@ -138,32 +138,23 @@ nonisolated final class StatusesTable: DatabaseTable, Sendable { func fetchArticleIDsForStatusesWithoutArticlesNewerThan(_ cutoffDate: Date, _ completion: @escaping ArticleIDsCompletionBlock) { queue.runInDatabase { databaseResult in - var error: DatabaseError? - var articleIDs = Set() - - func makeDatabaseCall(_ database: FMDatabase) { - let sql = "select articleID from statuses s where (starred=1 or dateArrived>?) and not exists (select 1 from articles a where a.articleID = s.articleID);" - if let resultSet = database.executeQuery(sql, withArgumentsIn: [cutoffDate]) { - articleIDs = resultSet.mapToSet(self.articleIDWithRow) - } - } + let result: Result, Error> switch databaseResult { case .success(let database): - makeDatabaseCall(database) + let sql = "select articleID from statuses s where (starred=1 or dateArrived>?) and not exists (select 1 from articles a where a.articleID = s.articleID);" + if let resultSet = database.executeQuery(sql, withArgumentsIn: [cutoffDate]) { + let articleIDs = resultSet.mapToSet(self.articleIDWithRow) + result = .success(articleIDs) + } else { + result = .success(Set()) + } case .failure(let databaseError): - error = databaseError + result = .failure(databaseError) } - if let error = error { - DispatchQueue.main.async { - completion(.failure(error)) - } - } - else { - DispatchQueue.main.async { - completion(.success(articleIDs)) - } + DispatchQueue.main.async { + completion(result) } } } @@ -235,7 +226,7 @@ nonisolated final class StatusesTable: DatabaseTable, Sendable { // MARK: - Private -private extension StatusesTable { +nonisolated private extension StatusesTable { // MARK: - Cache diff --git a/Modules/RSCore/Sources/RSCore/Shared/MainThreadOperation.swift b/Modules/RSCore/Sources/RSCore/Shared/MainThreadOperation.swift index 69e3be4c7..d2ce11c44 100644 --- a/Modules/RSCore/Sources/RSCore/Shared/MainThreadOperation.swift +++ b/Modules/RSCore/Sources/RSCore/Shared/MainThreadOperation.swift @@ -105,9 +105,16 @@ nonisolated open class MainThreadOperation: Hashable, @unchecked Sendable { } /// Call when completed. This will trigger calling completionBlock. - @MainActor public func didComplete() { - assert(Thread.isMainThread) - operationQueue?.operationDidComplete(self) + nonisolated public func didComplete() { + if Thread.isMainThread { + MainActor.assumeIsolated { + operationQueue?.operationDidComplete(self) + } + } else { + Task { @MainActor in + didComplete() + } + } } /// Override to be notified when the operation is complete. diff --git a/Modules/RSDatabase/Sources/RSDatabase/Database.swift b/Modules/RSDatabase/Sources/RSDatabase/Database.swift index abeb72250..c73733905 100644 --- a/Modules/RSDatabase/Sources/RSDatabase/Database.swift +++ b/Modules/RSDatabase/Sources/RSDatabase/Database.swift @@ -9,7 +9,7 @@ import Foundation import RSDatabaseObjC -public enum DatabaseError: Error, LocalizedError, Sendable { +nonisolated public enum DatabaseError: Error, LocalizedError, Sendable { case isSuspended // On iOS, to support background refreshing, a database may be suspended. public var errorDescription: String? { @@ -27,7 +27,7 @@ public typealias DatabaseResult = Result public typealias DatabaseBlock = @Sendable (DatabaseResult) -> Void /// Completion block that provides an optional DatabaseError. -public typealias DatabaseCompletionBlock = (DatabaseError?) -> Void +public typealias DatabaseCompletionBlock = @Sendable (DatabaseError?) -> Void /// Result type for fetching an Int or getting a DatabaseError. public typealias DatabaseIntResult = Result diff --git a/Modules/SyncDatabase/Sources/SyncDatabase/SyncStatus.swift b/Modules/SyncDatabase/Sources/SyncDatabase/SyncStatus.swift index 85f8b7cbe..bc0e732de 100644 --- a/Modules/SyncDatabase/Sources/SyncDatabase/SyncStatus.swift +++ b/Modules/SyncDatabase/Sources/SyncDatabase/SyncStatus.swift @@ -10,8 +10,8 @@ import Foundation import Articles import RSDatabase -nonisolated public struct SyncStatus: Hashable, Equatable { - public enum Key: String { +nonisolated public struct SyncStatus: Hashable, Equatable, Sendable { + public enum Key: String, Sendable { case read case starred case deleted diff --git a/Shared/SmartFeeds/SmartFeed.swift b/Shared/SmartFeeds/SmartFeed.swift index 97c7e4fa9..fa75d7ea0 100644 --- a/Shared/SmartFeeds/SmartFeed.swift +++ b/Shared/SmartFeeds/SmartFeed.swift @@ -111,8 +111,10 @@ private extension SmartFeed { guard let singleUnreadCountResult, let accountUnreadCount = try? singleUnreadCountResult.get() else { return } - self.unreadCounts[account.accountID] = accountUnreadCount - self.updateUnreadCount() + Task { @MainActor in + self.unreadCounts[account.accountID] = accountUnreadCount + self.updateUnreadCount() + } } } diff --git a/Shared/Timeline/FetchRequestOperation.swift b/Shared/Timeline/FetchRequestOperation.swift index f0864140e..c3a58ff32 100644 --- a/Shared/Timeline/FetchRequestOperation.swift +++ b/Shared/Timeline/FetchRequestOperation.swift @@ -33,7 +33,7 @@ typealias FetchRequestOperationResultBlock = (Set
, FetchRequestOperatio self.resultBlock = resultBlock } - func run(_ completion: @escaping (FetchRequestOperation) -> Void) { + @MainActor func run(_ completion: @escaping (FetchRequestOperation) -> Void) { precondition(Thread.isMainThread) precondition(!isFinished) @@ -62,7 +62,7 @@ typealias FetchRequestOperationResultBlock = (Set
, FetchRequestOperatio var fetchersReturned = 0 var fetchedArticles = Set
() - func process(_ articles: Set
) { + @MainActor func process(_ articles: Set
) { precondition(Thread.isMainThread) guard !self.isCanceled else { callCompletionIfNeeded() @@ -84,12 +84,16 @@ typealias FetchRequestOperationResultBlock = (Set
, FetchRequestOperatio if (fetcher as? SidebarItem)?.readFiltered(readFilterEnabledTable: readFilterEnabledTable) ?? true { fetcher.fetchUnreadArticlesAsync { articleSetResult in let articles = (try? articleSetResult.get()) ?? Set
() - process(articles) + Task { @MainActor in + process(articles) + } } } else { fetcher.fetchArticlesAsync { articleSetResult in let articles = (try? articleSetResult.get()) ?? Set
() - process(articles) + Task { @MainActor in + process(articles) + } } } diff --git a/Shared/Widget/WidgetDataEncoder.swift b/Shared/Widget/WidgetDataEncoder.swift index 116276832..0bc6c1057 100644 --- a/Shared/Widget/WidgetDataEncoder.swift +++ b/Shared/Widget/WidgetDataEncoder.swift @@ -75,63 +75,69 @@ public final class WidgetDataEncoder { dispatchGroup.enter() AccountManager.shared.fetchArticlesAsync(.unread(fetchLimit)) { (articleSetResult) in - switch articleSetResult { - case .success(let articles): - for article in articles { - let latestArticle = LatestArticle(id: article.sortableArticleID, - feedTitle: article.sortableName, - articleTitle: ArticleStringFormatter.truncatedTitle(article).isEmpty ? ArticleStringFormatter.truncatedSummary(article) : ArticleStringFormatter.truncatedTitle(article), - articleSummary: article.summary, - feedIconPath: self.writeImageDataToSharedContainer(article.iconImage()?.image.dataRepresentation()), - pubDate: article.datePublished?.description ?? "") - unread.append(latestArticle) + MainActor.assumeIsolated { + switch articleSetResult { + case .success(let articles): + for article in articles { + let latestArticle = LatestArticle(id: article.sortableArticleID, + feedTitle: article.sortableName, + articleTitle: ArticleStringFormatter.truncatedTitle(article).isEmpty ? ArticleStringFormatter.truncatedSummary(article) : ArticleStringFormatter.truncatedTitle(article), + articleSummary: article.summary, + feedIconPath: self.writeImageDataToSharedContainer(article.iconImage()?.image.dataRepresentation()), + pubDate: article.datePublished?.description ?? "") + unread.append(latestArticle) + } + case .failure(let databaseError): + groupError = databaseError } - case .failure(let databaseError): - groupError = databaseError + dispatchGroup.leave() } - dispatchGroup.leave() } var starred = [LatestArticle]() dispatchGroup.enter() AccountManager.shared.fetchArticlesAsync(.starred(fetchLimit)) { (articleSetResult) in - switch articleSetResult { - case .success(let articles): - for article in articles { - let latestArticle = LatestArticle(id: article.sortableArticleID, - feedTitle: article.sortableName, - articleTitle: ArticleStringFormatter.truncatedTitle(article).isEmpty ? ArticleStringFormatter.truncatedSummary(article) : ArticleStringFormatter.truncatedTitle(article), - articleSummary: article.summary, - feedIconPath: self.writeImageDataToSharedContainer(article.iconImage()?.image.dataRepresentation()), - pubDate: article.datePublished?.description ?? "") - starred.append(latestArticle) + MainActor.assumeIsolated { + switch articleSetResult { + case .success(let articles): + for article in articles { + let latestArticle = LatestArticle(id: article.sortableArticleID, + feedTitle: article.sortableName, + articleTitle: ArticleStringFormatter.truncatedTitle(article).isEmpty ? ArticleStringFormatter.truncatedSummary(article) : ArticleStringFormatter.truncatedTitle(article), + articleSummary: article.summary, + feedIconPath: self.writeImageDataToSharedContainer(article.iconImage()?.image.dataRepresentation()), + pubDate: article.datePublished?.description ?? "") + starred.append(latestArticle) + } + case .failure(let databaseError): + groupError = databaseError } - case .failure(let databaseError): - groupError = databaseError + dispatchGroup.leave() } - dispatchGroup.leave() } var today = [LatestArticle]() dispatchGroup.enter() AccountManager.shared.fetchArticlesAsync(.today(fetchLimit)) { (articleSetResult) in - switch articleSetResult { - case .success(let articles): - for article in articles { - let latestArticle = LatestArticle(id: article.sortableArticleID, - feedTitle: article.sortableName, - articleTitle: ArticleStringFormatter.truncatedTitle(article).isEmpty ? ArticleStringFormatter.truncatedSummary(article) : ArticleStringFormatter.truncatedTitle(article), - articleSummary: article.summary, - feedIconPath: self.writeImageDataToSharedContainer(article.iconImage()?.image.dataRepresentation()), - pubDate: article.datePublished?.description ?? "") - today.append(latestArticle) + MainActor.assumeIsolated { + switch articleSetResult { + case .success(let articles): + for article in articles { + let latestArticle = LatestArticle(id: article.sortableArticleID, + feedTitle: article.sortableName, + articleTitle: ArticleStringFormatter.truncatedTitle(article).isEmpty ? ArticleStringFormatter.truncatedSummary(article) : ArticleStringFormatter.truncatedTitle(article), + articleSummary: article.summary, + feedIconPath: self.writeImageDataToSharedContainer(article.iconImage()?.image.dataRepresentation()), + pubDate: article.datePublished?.description ?? "") + today.append(latestArticle) + } + case .failure(let databaseError): + groupError = databaseError } - case .failure(let databaseError): - groupError = databaseError + dispatchGroup.leave() } - dispatchGroup.leave() } dispatchGroup.notify(queue: .main) {