From 2fbce1b63c4ac481d44cc5cf3fcca03f8be27f21 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Sat, 30 May 2026 11:12:29 -0700 Subject: [PATCH] Back off Feedly status sync to 30 minutes when last sync had no changes. --- Modules/Account/Sources/Account/Account.swift | 11 +- .../Sources/Account/AccountDelegate.swift | 4 +- .../Sources/Account/AccountManager.swift | 17 +- .../CloudKit/CloudKitAccountDelegate.swift | 6 +- .../Feedbin/FeedbinAccountDelegate.swift | 4 +- .../Feedly/FeedlyAccountDelegate.swift | 187 ++++++++++++++++-- .../LocalAccount/LocalAccountDelegate.swift | 3 +- .../NewsBlur/NewsBlurAccountDelegate.swift | 4 +- .../ReaderAPI/ReaderAPIAccountDelegate.swift | 7 +- Shared/Timer/ArticleStatusSyncTimer.swift | 17 +- iOS/AppDelegate.swift | 2 +- 11 files changed, 228 insertions(+), 34 deletions(-) diff --git a/Modules/Account/Sources/Account/Account.swift b/Modules/Account/Sources/Account/Account.swift index 68478e0d5..0d7238825 100644 --- a/Modules/Account/Sources/Account/Account.swift +++ b/Modules/Account/Sources/Account/Account.swift @@ -477,6 +477,7 @@ public enum FetchType { kind: ActivityKind, detail: String? = nil, successMessage: ((T) -> String?)? = nil, + durationIsSignificant: ((T) -> Bool)? = nil, _ work: () async throws -> T ) async throws -> T { let activityLog = ActivityLog.shared @@ -484,7 +485,8 @@ public enum FetchType { activityLog.didStart(id: id) do { let result = try await work() - activityLog.didComplete(id: id, message: successMessage?(result)) + let significant = durationIsSignificant?(result) ?? true + activityLog.didComplete(id: id, message: successMessage?(result), durationIsSignificant: significant) return result } catch { activityLog.didFail(id: id, error: error) @@ -498,6 +500,7 @@ public enum FetchType { kind: ActivityKind, detail: String? = nil, successMessage: ((T) -> String?)? = nil, + durationIsSignificant: ((T) -> Bool)? = nil, _ work: () throws -> T ) rethrows -> T { let activityLog = ActivityLog.shared @@ -505,7 +508,8 @@ public enum FetchType { activityLog.didStart(id: id) do { let result = try work() - activityLog.didComplete(id: id, message: successMessage?(result)) + let significant = durationIsSignificant?(result) ?? true + activityLog.didComplete(id: id, message: successMessage?(result), durationIsSignificant: significant) return result } catch { activityLog.didFail(id: id, error: error) @@ -519,7 +523,8 @@ public enum FetchType { try await delegate.sendArticleStatus(for: self) } - public func syncArticleStatus() async throws { + @discardableResult + public func syncArticleStatus() async throws -> Bool { try await delegate.syncArticleStatus(for: self) } diff --git a/Modules/Account/Sources/Account/AccountDelegate.swift b/Modules/Account/Sources/Account/AccountDelegate.swift index 405a24cf0..e4c7bae79 100644 --- a/Modules/Account/Sources/Account/AccountDelegate.swift +++ b/Modules/Account/Sources/Account/AccountDelegate.swift @@ -25,7 +25,9 @@ import Secrets func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable: Any]) async func refreshAll(for account: Account) async throws - func syncArticleStatus(for account: Account) async throws + /// Returns `true` if any meaningful work was done (statuses sent or local + /// statuses changed); `false` if the round was a no-op. + func syncArticleStatus(for account: Account) async throws -> Bool func sendArticleStatus(for account: Account) async throws func refreshArticleStatus(for account: Account) async throws diff --git a/Modules/Account/Sources/Account/AccountManager.swift b/Modules/Account/Sources/Account/AccountManager.swift index c29998186..a5f350452 100644 --- a/Modules/Account/Sources/Account/AccountManager.swift +++ b/Modules/Account/Sources/Account/AccountManager.swift @@ -344,13 +344,24 @@ import ActivityLog } } - public func syncArticleStatusAll() async { - await withTaskGroup(of: Void.self, isolation: MainActor.shared) { group in + /// Returns `true` if any account reported meaningful work this round; + /// `false` only if every account was idle. + @discardableResult + public func syncArticleStatusAll() async -> Bool { + await withTaskGroup(of: Bool.self, isolation: MainActor.shared) { group in for account in activeAccounts { group.addTask { - try? await account.syncArticleStatus() + (try? await account.syncArticleStatus()) ?? false } } + + var anyWork = false + for await didWork in group { + if didWork { + anyWork = true + } + } + return anyWork } } diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift index cfe65439b..9805e328a 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift @@ -134,12 +134,12 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete") } - func syncArticleStatus(for account: Account) async throws { + func syncArticleStatus(for account: Account) async throws -> Bool { Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") if let lastNoChangeSyncDate, Date().timeIntervalSince(lastNoChangeSyncDate) < Self.noChangeBackoffInterval { Self.logger.debug("CloudKitAccountDelegate: Skipping sync — no changes on last check, backing off") - return + return true } try await sendArticleStatus(for: account) @@ -153,6 +153,8 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { await cleanUpContentRecordsIfNeeded() Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete") + // CloudKit has its own per-account no-change backoff (lastNoChangeSyncDate). + return true } private var articlesZoneHasNoChanges: Bool { diff --git a/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift b/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift index cff911b7e..727ec1fbe 100644 --- a/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift +++ b/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift @@ -101,9 +101,11 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable { } } - func syncArticleStatus(for account: Account) async throws { + func syncArticleStatus(for account: Account) async throws -> Bool { try await sendArticleStatus(for: account) try await refreshArticleStatus(for: account) + // This delegate doesn't track per-sync change counts. + return true } func sendArticleStatus(for account: Account) async throws { diff --git a/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift b/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift index d25009516..72ec20e9c 100644 --- a/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift +++ b/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift @@ -158,7 +158,7 @@ import Secrets progressInfo = ProgressInfo() } - func syncArticleStatus(for account: Account) async throws { + func syncArticleStatus(for account: Account) async throws -> Bool { refreshProgress.reset() refreshProgress.addTasks(2) progressInfo = ProgressInfo() @@ -167,25 +167,40 @@ import Secrets progressInfo = ProgressInfo() } - try await sendArticleStatus(for: account) + let sentCount = try await sendArticleStatusReturningCount(for: account) refreshProgress.completeTask() - try await refreshArticleStatus(for: account) + let refreshCounts = try await refreshArticleStatusReturningCounts(for: account) refreshProgress.completeTask() + + return sentCount > 0 || refreshCounts.totalChanged > 0 } func sendArticleStatus(for account: Account) async throws { + _ = try await sendArticleStatusReturningCount(for: account) + } + + /// Sends queued local status changes upstream. Returns the count successfully sent. + private func sendArticleStatusReturningCount(for account: Account) async throws -> Int { Self.logger.info("Feedly: Sending article statuses") defer { Self.logger.info("Feedly: Finished sending article statuses") } + let successMessage: (Int) -> String? = { count in + Self.sendStatusMessage(count: count) + } + let durationIsSignificant: (Int) -> Bool = { count in + count > 0 + } + do { - try await account.logActivity(kind: .sendArticleStatuses) { + return try await account.logActivity(kind: .sendArticleStatuses, successMessage: successMessage, durationIsSignificant: durationIsSignificant) { () -> Int in guard let syncStatuses = try await syncDatabase.selectForProcessing() else { - return + return 0 } var savedError: Error? + var sentCount = 0 let pairings: [(key: SyncStatus.Key, flag: Bool, action: FeedlyMarkAction)] = [ (.read, false, .unread), (.read, true, .read), @@ -202,6 +217,7 @@ import Secrets do { try await caller.mark(articleIDs, as: pairing.action) try? await syncDatabase.deleteSelectedForProcessing(articleIDs) + sentCount += articleIDs.count } catch { Self.logger.error("Feedly: Article status sync call failed: \(error.localizedDescription)") try? await syncDatabase.resetSelectedForProcessing(articleIDs) @@ -212,6 +228,7 @@ import Secrets if let savedError { throw savedError } + return sentCount } } catch { postSyncError(error, account: account, operation: "Sending article status") @@ -219,28 +236,45 @@ import Secrets } } + func refreshArticleStatus(for account: Account) async throws { + _ = try await refreshArticleStatusReturningCounts(for: account) + } + /// Attempt to bring local read/starred statuses in line with the remote ones. /// If the user is using another Feedly client at roughly the same time as this app, /// this app does its part to ensure articles have a consistent status between both. - func refreshArticleStatus(for account: Account) async throws { + /// Returns counts of articles whose unread/starred state actually flipped. + private func refreshArticleStatusReturningCounts(for account: Account) async throws -> StatusRefreshCounts { Self.logger.info("Feedly: Refreshing article statuses") guard let credentials else { - return + return StatusRefreshCounts() } - try await account.logActivity(kind: .refreshArticleStatuses) { + let successMessage: (StatusRefreshCounts) -> String? = { counts in + Self.refreshStatusMessage(counts: counts) + } + let durationIsSignificant: (StatusRefreshCounts) -> Bool = { counts in + counts.totalChanged > 0 + } + + return try await account.logActivity(kind: .refreshArticleStatuses, successMessage: successMessage, durationIsSignificant: durationIsSignificant) { () -> StatusRefreshCounts in var refreshError: Error? + var counts = StatusRefreshCounts() do { - try await ingestUnreadArticleIDs(for: account, userID: credentials.username) + let unread = try await ingestUnreadArticleIDs(for: account, userID: credentials.username) + counts.unreadAdded = unread.added + counts.unreadRemoved = unread.removed } catch { refreshError = error Self.logger.error("Feedly: Ingesting unread article IDs failed: \(error.localizedDescription)") } do { - try await ingestStarredArticleIDs(for: account, userID: credentials.username) + let starred = try await ingestStarredArticleIDs(for: account, userID: credentials.username) + counts.starredAdded = starred.added + counts.starredRemoved = starred.removed } catch { refreshError = error Self.logger.error("Feedly: Ingesting starred article IDs failed: \(error.localizedDescription)") @@ -251,6 +285,7 @@ import Secrets postSyncError(refreshError, account: account, operation: "Refreshing article status") throw refreshError } + return counts } } @@ -618,11 +653,39 @@ private extension FeedlyAccountDelegate { } func refreshFeedList(for account: Account) async throws { + let successMessage: (FeedListChanges) -> String? = { changes in + Self.feedListMessage(changes: changes) + } + let durationIsSignificant: (FeedListChanges) -> Bool = { changes in + changes.totalChanged > 0 + } + do { - try await account.logActivity(kind: .refreshFeedList) { + try await account.logActivity(kind: .refreshFeedList, successMessage: successMessage, durationIsSignificant: durationIsSignificant) { () -> FeedListChanges in + // Snapshot before reconciliation so we can diff what actually changed. + let foldersBefore = account.folders ?? Set() + let feedsBefore = account.flattenedFeeds() + let feedNamesBefore = Dictionary(uniqueKeysWithValues: feedsBefore.map { ($0.feedID, $0.nameForDisplay) }) + let collections = try await caller.getCollections() let pairs = mirrorCollectionsAsFolders(collections, in: account) syncFeedsForCollectionFolders(pairs, in: account) + + let foldersAfter = account.folders ?? Set() + let feedsAfter = account.flattenedFeeds() + + let feedsRenamed = feedsAfter.reduce(into: 0) { count, feed in + if let before = feedNamesBefore[feed.feedID], before != feed.nameForDisplay { + count += 1 + } + } + + return FeedListChanges( + foldersAdded: foldersAfter.subtracting(foldersBefore).count, + foldersRemoved: foldersBefore.subtracting(foldersAfter).count, + feedsAdded: feedsAfter.subtracting(feedsBefore).count, + feedsRemoved: feedsBefore.subtracting(feedsAfter).count, + feedsRenamed: feedsRenamed) } } catch { postSyncError(error, account: account, operation: "Refreshing feed list") @@ -645,7 +708,10 @@ private extension FeedlyAccountDelegate { /// Mirror the remote unread set onto local statuses. /// Articles in the remote unread set become unread locally; the rest become read. /// Pending local edits are excluded so we don't temporarily clobber them. - func ingestUnreadArticleIDs(for account: Account, userID: String) async throws { + /// Returns counts of articles whose unread status actually flipped: + /// `added` became unread, `removed` became read. + @discardableResult + func ingestUnreadArticleIDs(for account: Account, userID: String) async throws -> (added: Int, removed: Int) { let resource = FeedlyCategoryResourceID.Global.all(for: userID) let remoteUnreadIDs = try await collectStreamIDs(for: resource, unreadOnly: true) @@ -654,13 +720,20 @@ private extension FeedlyAccountDelegate { let localUnreadIDs = try await account.fetchUnreadArticleIDsAsync() - try await account.markAsUnreadAsync(articleIDs: adjustedRemoteUnreadIDs) + let newlyUnread = adjustedRemoteUnreadIDs.subtracting(localUnreadIDs) let toMarkRead = localUnreadIDs.subtracting(adjustedRemoteUnreadIDs) + + try await account.markAsUnreadAsync(articleIDs: adjustedRemoteUnreadIDs) try await account.markAsReadAsync(articleIDs: toMarkRead) + + return (added: newlyUnread.count, removed: toMarkRead.count) } /// Mirror the remote starred set onto local statuses. - func ingestStarredArticleIDs(for account: Account, userID: String) async throws { + /// Returns counts of articles whose starred status actually flipped: + /// `added` became starred, `removed` became unstarred. + @discardableResult + func ingestStarredArticleIDs(for account: Account, userID: String) async throws -> (added: Int, removed: Int) { let resource = FeedlyTagResourceID.Global.saved(for: userID) let remoteStarredIDs = try await collectStreamIDs(for: resource, unreadOnly: nil) @@ -669,9 +742,13 @@ private extension FeedlyAccountDelegate { let localStarredIDs = try await account.fetchStarredArticleIDsAsync() - try await account.markAsStarredAsync(articleIDs: adjustedRemoteStarredIDs) + let newlyStarred = adjustedRemoteStarredIDs.subtracting(localStarredIDs) let toUnstar = localStarredIDs.subtracting(adjustedRemoteStarredIDs) + + try await account.markAsStarredAsync(articleIDs: adjustedRemoteStarredIDs) try await account.markAsUnstarredAsync(articleIDs: toUnstar) + + return (added: newlyStarred.count, removed: toUnstar.count) } /// IDs of articles updated on Feedly since `newerThan`. @@ -790,3 +867,83 @@ extension FeedlyAccountDelegate: FeedlyAPICallerDelegate { } } } + +// MARK: - Activity Log Messages + +extension FeedlyAccountDelegate { + + /// Counts of articles whose status actually flipped during a refresh. + struct StatusRefreshCounts { + var unreadAdded = 0 + var unreadRemoved = 0 + var starredAdded = 0 + var starredRemoved = 0 + + var totalChanged: Int { + unreadAdded + unreadRemoved + starredAdded + starredRemoved + } + } + + /// Counts of folder/feed structural changes during a feed-list refresh. + struct FeedListChanges { + var foldersAdded = 0 + var foldersRemoved = 0 + var feedsAdded = 0 + var feedsRemoved = 0 + var feedsRenamed = 0 + + var totalChanged: Int { + foldersAdded + foldersRemoved + feedsAdded + feedsRemoved + feedsRenamed + } + } + + static func sendStatusMessage(count: Int) -> String { + if count == 0 { + return "No statuses to send" + } + return "\(count) status\(count == 1 ? "" : "es") sent" + } + + static func refreshStatusMessage(counts: StatusRefreshCounts) -> String { + var parts = [String]() + if counts.unreadAdded > 0 { + parts.append("\(counts.unreadAdded) marked unread") + } + if counts.unreadRemoved > 0 { + parts.append("\(counts.unreadRemoved) marked read") + } + if counts.starredAdded > 0 { + parts.append("\(counts.starredAdded) starred") + } + if counts.starredRemoved > 0 { + parts.append("\(counts.starredRemoved) unstarred") + } + if parts.isEmpty { + return "No changes" + } + return parts.joined(separator: ", ") + } + + static func feedListMessage(changes: FeedListChanges) -> String { + var parts = [String]() + if changes.foldersAdded > 0 { + parts.append("\(changes.foldersAdded) folder\(changes.foldersAdded == 1 ? "" : "s") added") + } + if changes.foldersRemoved > 0 { + parts.append("\(changes.foldersRemoved) folder\(changes.foldersRemoved == 1 ? "" : "s") removed") + } + if changes.feedsAdded > 0 { + parts.append("\(changes.feedsAdded) feed\(changes.feedsAdded == 1 ? "" : "s") added") + } + if changes.feedsRemoved > 0 { + parts.append("\(changes.feedsRemoved) feed\(changes.feedsRemoved == 1 ? "" : "s") removed") + } + if changes.feedsRenamed > 0 { + parts.append("\(changes.feedsRenamed) feed\(changes.feedsRenamed == 1 ? "" : "s") renamed") + } + if parts.isEmpty { + return "No changes" + } + return parts.joined(separator: ", ") + } +} diff --git a/Modules/Account/Sources/Account/LocalAccount/LocalAccountDelegate.swift b/Modules/Account/Sources/Account/LocalAccount/LocalAccountDelegate.swift index e18b4d855..aa2ee1f95 100644 --- a/Modules/Account/Sources/Account/LocalAccount/LocalAccountDelegate.swift +++ b/Modules/Account/Sources/Account/LocalAccount/LocalAccountDelegate.swift @@ -54,7 +54,8 @@ import Secrets account.lastRefreshCompletedDate = Date() } - @MainActor func syncArticleStatus(for account: Account) async throws { + @MainActor func syncArticleStatus(for account: Account) async throws -> Bool { + false } @MainActor func sendArticleStatus(for account: Account) async throws { diff --git a/Modules/Account/Sources/Account/NewsBlur/NewsBlurAccountDelegate.swift b/Modules/Account/Sources/Account/NewsBlur/NewsBlurAccountDelegate.swift index 3538057ce..3ee0d4e55 100644 --- a/Modules/Account/Sources/Account/NewsBlur/NewsBlurAccountDelegate.swift +++ b/Modules/Account/Sources/Account/NewsBlur/NewsBlurAccountDelegate.swift @@ -103,9 +103,11 @@ import Secrets } } - @MainActor func syncArticleStatus(for account: Account) async throws { + @MainActor func syncArticleStatus(for account: Account) async throws -> Bool { try await sendArticleStatus(for: account) try await refreshArticleStatus(for: account) + // This delegate doesn't track per-sync change counts. + return true } @MainActor func sendArticleStatus(for account: Account) async throws { diff --git a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift index 706709e24..ed771b28b 100644 --- a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift +++ b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift @@ -165,15 +165,18 @@ final class ReaderAPIAccountDelegate: AccountDelegate { } } - @MainActor func syncArticleStatus(for account: Account) async throws { + @MainActor func syncArticleStatus(for account: Account) async throws -> Bool { guard variant != .inoreader else { - return + // Inoreader: no-op for this delegate. + return false } Self.logger.debug("ReaderAPIAccountDelegate: syncArticleStatus") try await sendArticleStatus(for: account) try await refreshArticleStatus(for: account) + // This delegate doesn't track per-sync change counts. + return true } public func sendArticleStatus(for account: Account) async throws { diff --git a/Shared/Timer/ArticleStatusSyncTimer.swift b/Shared/Timer/ArticleStatusSyncTimer.swift index f537ca744..f6e61a03b 100644 --- a/Shared/Timer/ArticleStatusSyncTimer.swift +++ b/Shared/Timer/ArticleStatusSyncTimer.swift @@ -12,13 +12,16 @@ import Account @MainActor final class ArticleStatusSyncTimer { static let shared = ArticleStatusSyncTimer() - private static let intervalSeconds = Double(120) + private static let normalIntervalSeconds: TimeInterval = 120 // 2 minutes + private static let idleBackoffIntervalSeconds: TimeInterval = 1800 // 30 minutes var shuttingDown = false private var internalTimer: Timer? private var lastTimedRefresh: Date? private let launchTime = Date() + /// True when the most recent timed run was a no-op; the next fire is pushed out. + private var lastRunWasIdle = false func fireOldTimer() { if let timer = internalTimer { @@ -53,10 +56,11 @@ import Account return } + let interval = lastRunWasIdle ? Self.idleBackoffIntervalSeconds : Self.normalIntervalSeconds let lastRefreshDate = lastTimedRefresh ?? launchTime - var nextRefreshTime = lastRefreshDate.addingTimeInterval(ArticleStatusSyncTimer.intervalSeconds) + var nextRefreshTime = lastRefreshDate.addingTimeInterval(interval) if nextRefreshTime < Date() { - nextRefreshTime = Date().addingTimeInterval(ArticleStatusSyncTimer.intervalSeconds) + nextRefreshTime = Date().addingTimeInterval(interval) } if let currentNextFireDate = internalTimer?.fireDate, currentNextFireDate == nextRefreshTime { return @@ -78,6 +82,11 @@ import Account lastTimedRefresh = Date() update() - AccountManager.shared.syncArticleStatusAllWithoutWaiting() + Task { + let didWork = await AccountManager.shared.syncArticleStatusAll() + self.lastRunWasIdle = !didWork + // Re-schedule now that we know whether to back off. + self.update() + } } } diff --git a/iOS/AppDelegate.swift b/iOS/AppDelegate.swift index 857445145..6a8e50eb2 100644 --- a/iOS/AppDelegate.swift +++ b/iOS/AppDelegate.swift @@ -467,7 +467,7 @@ private extension AppDelegate { account.markArticles(singleArticleSet, statusKey: statusKey, flag: true) { _ in } Task { @MainActor in - try? await account.syncArticleStatus() + _ = try? await account.syncArticleStatus() prepareAccountsForBackground() suspendApplication() }