From eb82dd3ce3fe2b370261f9cdb677400f7e2f3535 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Sat, 13 Jun 2026 14:11:58 -0700 Subject: [PATCH] Fix hang in WidgetDataEncoder by fetching async. Use count queries in places where we were fetching articles just to get counts. --- Modules/Account/Sources/Account/Account.swift | 8 ++++ .../Sources/Account/AccountManager.swift | 27 ++++++++++++ .../ArticlesDatabase/ArticlesDatabase.swift | 16 +++++++ .../ArticlesDatabase/ArticlesTable.swift | 43 +++++++++++++++++++ Shared/Widget/WidgetDataEncoder.swift | 42 ++++++++++++------ iOS/AppDelegate.swift | 2 +- 6 files changed, 125 insertions(+), 13 deletions(-) diff --git a/Modules/Account/Sources/Account/Account.swift b/Modules/Account/Sources/Account/Account.swift index b792f034f..78eec5a7d 100644 --- a/Modules/Account/Sources/Account/Account.swift +++ b/Modules/Account/Sources/Account/Account.swift @@ -884,6 +884,14 @@ public enum FetchType { await database.fetchUnreadCountForTodayAsync(feedIDs: flattenedFeedsIDs) } + public func fetchCountForTodayArticlesAsync() async -> Int { + await database.fetchTodayArticlesCountAsync(feedIDs: flattenedFeedsIDs) + } + + public func fetchCountForStarredArticlesAsync() async -> Int { + await database.fetchStarredArticlesCountAsync(feedIDs: flattenedFeedsIDs) + } + public func fetchUnreadArticleIDsAsync() async -> Set { await database.fetchUnreadArticleIDsAsync() } diff --git a/Modules/Account/Sources/Account/AccountManager.swift b/Modules/Account/Sources/Account/AccountManager.swift index b81486d73..8be3cd233 100644 --- a/Modules/Account/Sources/Account/AccountManager.swift +++ b/Modules/Account/Sources/Account/AccountManager.swift @@ -441,6 +441,33 @@ import ActivityLog return count } + public func fetchCountForStarredArticlesAsync() async -> Int { + precondition(Thread.isMainThread) + var count = 0 + for account in activeAccounts { + count += await account.fetchCountForStarredArticlesAsync() + } + return count + } + + public func fetchCountForTodayArticlesAsync() async -> Int { + precondition(Thread.isMainThread) + var count = 0 + for account in activeAccounts { + count += await account.fetchCountForTodayArticlesAsync() + } + return count + } + + public func fetchUnreadCountForTodayAsync() async -> Int { + precondition(Thread.isMainThread) + var count = 0 + for account in activeAccounts { + count += await account.fetchUnreadCountForTodayAsync() + } + return count + } + // MARK: - Vacuum public func vacuumAllDatabases() async { diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift index 71878f6e9..2c0a2017f 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift @@ -289,6 +289,22 @@ public struct ArticleCounts: Sendable { } } + public func fetchTodayArticlesCountAsync(feedIDs: Set) async -> Int { + await withCheckedContinuation { continuation in + articlesTable.fetchArticlesCountSince(feedIDs, todayCutoffDate()) { count in + continuation.resume(returning: count) + } + } + } + + public func fetchStarredArticlesCountAsync(feedIDs: Set) async -> Int { + await withCheckedContinuation { continuation in + articlesTable.fetchStarredArticlesCountAsync(feedIDs) { count in + continuation.resume(returning: count) + } + } + } + // MARK: - Saving, Updating, and Deleting Articles /// Update articles and save new ones — for feed-based systems (local and iCloud). diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift index 2ceaa9460..f5a210a1a 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift @@ -442,6 +442,49 @@ final class ArticlesTable: DatabaseTable, Sendable { } } + func fetchArticlesCountSince(_ feedIDs: Set, _ cutoffDate: Date, _ completion: @escaping SingleUnreadCountCompletionBlock) { + // Total count (read and unread) since a cutoff date — today's count, for instance. + if feedIDs.isEmpty { + completion(0) + return + } + + queue.runInDatabase { database in + let placeholders = NSString.rs_SQLValueList(withPlaceholders: UInt(feedIDs.count))! + let sql = "select count(*) from articles natural join statuses where feedID in \(placeholders) and (datePublished > ? or (datePublished is null and dateArrived > ?));" + + var parameters = [Any]() + parameters += Array(feedIDs) as [Any] + parameters += [cutoffDate] as [Any] + parameters += [cutoffDate] as [Any] + + let count = self.numberWithSQLAndParameters(sql, parameters, in: database) + + DispatchQueue.main.async { + completion(count) + } + } + } + + func fetchStarredArticlesCountAsync(_ feedIDs: Set, _ completion: @escaping SingleUnreadCountCompletionBlock) { + if feedIDs.isEmpty { + completion(0) + return + } + + queue.runInDatabase { database in + let placeholders = NSString.rs_SQLValueList(withPlaceholders: UInt(feedIDs.count))! + let sql = "select count(*) from articles natural join statuses where feedID in \(placeholders) and starred=1;" + let parameters = Array(feedIDs) as [Any] + + let count = self.numberWithSQLAndParameters(sql, parameters, in: database) + + DispatchQueue.main.async { + completion(count) + } + } + } + // MARK: - Statuses func fetchUnreadArticleIDsAsync(_ completion: @escaping ArticleIDsCompletionBlock) { diff --git a/Shared/Widget/WidgetDataEncoder.swift b/Shared/Widget/WidgetDataEncoder.swift index b85efa9b4..3e20837b8 100644 --- a/Shared/Widget/WidgetDataEncoder.swift +++ b/Shared/Widget/WidgetDataEncoder.swift @@ -46,18 +46,35 @@ import Account } } + /// Fire-and-forget. Sets `isRunning` synchronously so the background-task wait loop + /// (see AppDelegate.waitToComplete) holds the app awake until encoding finishes. func encode() { guard !isRunning else { Self.logger.debug("WidgetDataEncoder: skipping encode because already in encode") return } - isRunning = true + Task { @MainActor in + await performEncode() + } + } + + /// Awaitable variant for callers that must finish encoding before suspending the app. + func encodeAndWait() async { + guard !isRunning else { + Self.logger.debug("WidgetDataEncoder: skipping encode because already in encode") + return + } + isRunning = true + await performEncode() + } + + private func performEncode() async { defer { isRunning = false } removeStaleFaviconsFromSharedContainer() - let latestData = fetchWidgetData() + let latestData = await fetchWidgetData() let encodedData: Data do { encodedData = try JSONEncoder().encode(latestData) @@ -110,23 +127,24 @@ import Account @MainActor private extension WidgetDataEncoder { - func fetchWidgetData() -> WidgetData { - let fetchedUnreadArticles = AccountManager.shared.fetchArticles(.unread(fetchLimit)) + func fetchWidgetData() async -> WidgetData { + let fetchedUnreadArticles = await AccountManager.shared.fetchArticlesAsync(.unread(fetchLimit)) let unreadArticles = sortedLatestArticles(fetchedUnreadArticles) - let fetchedStarredArticles = AccountManager.shared.fetchArticles(.starred(fetchLimit)) + let fetchedStarredArticles = await AccountManager.shared.fetchArticlesAsync(.starred(fetchLimit)) let starredArticles = sortedLatestArticles(fetchedStarredArticles) - let fetchedTodayArticles = AccountManager.shared.fetchArticles(.today(fetchLimit)) - let fetchedTodayTotal = AccountManager.shared.fetchArticles(.today()) - let fetchedTodayTotalCount = fetchedTodayTotal.count - let fetchedTodayUnreadCount = fetchedTodayTotal.filter({ $0.status.read == false }).count + let fetchedTodayArticles = await AccountManager.shared.fetchArticlesAsync(.today(fetchLimit)) let todayArticles = sortedLatestArticles(fetchedTodayArticles) + let totalTodayCount = await AccountManager.shared.fetchCountForTodayArticlesAsync() + let totalTodayUnreadCount = await AccountManager.shared.fetchUnreadCountForTodayAsync() + let totalStarredCount = await AccountManager.shared.fetchCountForStarredArticlesAsync() + let latestData = WidgetData(totalUnreadCount: SmartFeedsController.shared.unreadFeed.unreadCount, - totalTodayCount: fetchedTodayTotalCount, - totalTodayUnreadCount: fetchedTodayUnreadCount, - totalStarredCount: AccountManager.shared.fetchCountForStarredArticles(), + totalTodayCount: totalTodayCount, + totalTodayUnreadCount: totalTodayUnreadCount, + totalStarredCount: totalStarredCount, unreadArticles: unreadArticles, starredArticles: starredArticles, todayArticles: todayArticles, diff --git a/iOS/AppDelegate.swift b/iOS/AppDelegate.swift index fb853173b..20f7f775f 100644 --- a/iOS/AppDelegate.swift +++ b/iOS/AppDelegate.swift @@ -413,7 +413,7 @@ private extension AppDelegate { } await AccountManager.shared.refreshAll(errorHandler: ErrorHandler.log) if !AccountManager.shared.isSuspended { - WidgetDataEncoder.shared?.encode() + await WidgetDataEncoder.shared?.encodeAndWait() self.suspendApplication() Self.logger.info("Background refresh completed.") task.setTaskCompleted(success: true)