diff --git a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift index c422086ce..6d381d4af 100644 --- a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift +++ b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPIAccountDelegate.swift @@ -52,6 +52,13 @@ final class ReaderAPIAccountDelegate: AccountDelegate { private let caller: ReaderAPICaller private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "ReaderAPI") + // Set on a 429 Too Many Requests response. Refreshing and status syncing are skipped + // until this date so we don’t keep burning the shared per-application API quota. + // + private var rateLimitResumeDate: Date? + private static let defaultRetryAfter: TimeInterval = 60 * 60 + private static let zone1UsageThreshold = 0.9 + var progressInfo = ProgressInfo() { didSet { if progressInfo != oldValue { @@ -106,6 +113,9 @@ final class ReaderAPIAccountDelegate: AccountDelegate { guard let account else { return } + if shouldSkipBecauseRateLimited() { + return + } Self.logger.debug("ReaderAPIAccountDelegate: refreshAll") retrieveCredentialsIfNeeded(account) @@ -121,18 +131,29 @@ final class ReaderAPIAccountDelegate: AccountDelegate { try? await sendArticleStatus() refreshProgress.completeTask() - let articleIDs = try await account.logActivity(kind: .fetchArticleIDs, detail: "All articles", successMessage: { "\($0.count) article IDs" }, { - try await caller.retrieveItemIDs(type: .allForAccount, pageHandler: articleIDPageHandler(for: account, kind: .fetchArticleIDs)) - }) - refreshProgress.completeTask() + // The mark-as-read of all fetched article IDs and the unread download that + // corrects it are a pair — skipping just the second half would leave new + // articles wrongly marked read. Skip or run the whole reconcile together. + if shouldSkipStatusDownloadsToConserveQuota() { + refreshProgress.completeTask() + refreshProgress.completeTask() + } else { + let articleIDs = try await account.logActivity(kind: .fetchArticleIDs, detail: "All articles", successMessage: { "\($0.count) article IDs" }, { + try await caller.retrieveItemIDs(type: .allForAccount, pageHandler: articleIDPageHandler(for: account, kind: .fetchArticleIDs)) + }) + refreshProgress.completeTask() - _ = await account.markAsReadAsync(articleIDs: Set(articleIDs)) - try? await refreshArticleStatus() - refreshProgress.completeTask() + _ = await account.markAsReadAsync(articleIDs: Set(articleIDs)) + try? await refreshArticleStatus() + refreshProgress.completeTask() + } await refreshMissingArticles(account) refreshProgress.reset() } + } catch WebserviceError.tooManyRequests(let retryAfter) { + refreshProgress.reset() + noteRateLimited(retryAfter: retryAfter, account: account, operation: "Refreshing account") } catch { Self.logger.error("ReaderAPIAccountDelegate: refreshAll 1 — error \(error.localizedDescription)") refreshProgress.reset() @@ -165,27 +186,42 @@ final class ReaderAPIAccountDelegate: AccountDelegate { guard let account else { return false } + if shouldSkipBecauseRateLimited() { + return false + } Self.logger.debug("ReaderAPIAccountDelegate: syncArticleStatus") - let sentCount = try await sendArticleStatusReturningCount(for: account) + do { + let sentCount = try await sendArticleStatusReturningCount(for: account) - // Inoreader: skip downloading statuses, to conserve its API rate limits — but do send, - // since a send is a single cheap request and skipping it loses stars. - // - if variant == .inoreader { - return sentCount > 0 + // Inoreader: skip downloading statuses, to conserve its API rate limits — but do send, + // since a send is a single cheap request and skipping it loses stars. + // + if variant == .inoreader { + return sentCount > 0 + } + + let refreshChangedCount = try await refreshArticleStatusReturningCount(for: account) + return sentCount > 0 || refreshChangedCount > 0 + } catch WebserviceError.tooManyRequests(let retryAfter) { + noteRateLimited(retryAfter: retryAfter, account: account, operation: "Syncing article status") + return false } - - let refreshChangedCount = try await refreshArticleStatusReturningCount(for: account) - return sentCount > 0 || refreshChangedCount > 0 } public func sendArticleStatus() async throws { guard let account else { return } - _ = try await sendArticleStatusReturningCount(for: account) + if shouldSkipBecauseRateLimited() { + return + } + do { + _ = try await sendArticleStatusReturningCount(for: account) + } catch WebserviceError.tooManyRequests(let retryAfter) { + noteRateLimited(retryAfter: retryAfter, account: account, operation: "Sending article status") + } } /// Sends queued local status changes upstream. Returns the count successfully sent. @@ -228,7 +264,10 @@ final class ReaderAPIAccountDelegate: AccountDelegate { } if let savedError { - postSyncError(savedError, account: account, operation: "Sending article status") + // A 429 gets one Error Log entry from noteRateLimited, not one per send. + if !isTooManyRequests(savedError) { + postSyncError(savedError, account: account, operation: "Sending article status") + } throw savedError } return sentCount @@ -239,7 +278,14 @@ final class ReaderAPIAccountDelegate: AccountDelegate { guard let account else { return } - _ = try await refreshArticleStatusReturningCount(for: account) + if shouldSkipBecauseRateLimited() { + return + } + do { + _ = try await refreshArticleStatusReturningCount(for: account) + } catch WebserviceError.tooManyRequests(let retryAfter) { + noteRateLimited(retryAfter: retryAfter, account: account, operation: "Refreshing article status") + } } /// Brings local read/starred statuses in line with the server. Returns the count @@ -247,6 +293,10 @@ final class ReaderAPIAccountDelegate: AccountDelegate { @MainActor private func refreshArticleStatusReturningCount(for account: Account) async throws -> Int { Self.logger.debug("ReaderAPIAccountDelegate: refreshArticleStatus") + if shouldSkipStatusDownloadsToConserveQuota() { + return 0 + } + return try await account.logActivity(kind: .refreshArticleStatuses) { () -> Int in var changedCount = 0 var savedError: Error? @@ -270,7 +320,10 @@ final class ReaderAPIAccountDelegate: AccountDelegate { } if let savedError { - postSyncError(savedError, account: account, operation: "Refreshing article status") + // A 429 gets one Error Log entry from noteRateLimited, not one per refresh. + if !isTooManyRequests(savedError) { + postSyncError(savedError, account: account, operation: "Refreshing article status") + } throw savedError } return changedCount @@ -1131,6 +1184,55 @@ private extension ReaderAPIAccountDelegate { return markedStarred.count + markedUnstarred.count } + // MARK: - Rate Limiting + + /// True when a 429 response has paused syncing and the pause hasn’t expired. + private func shouldSkipBecauseRateLimited() -> Bool { + guard let rateLimitResumeDate else { + return false + } + guard rateLimitResumeDate > Date() else { + self.rateLimitResumeDate = nil + return false + } + Self.logger.info("ReaderAPIAccountDelegate: skipping — rate limited until \(rateLimitResumeDate)") + return true + } + + /// Pause syncing until the server’s Retry-After (or a default) and post one Error Log entry. + private func noteRateLimited(retryAfter: TimeInterval?, account: Account, operation: String) { + let alreadyRateLimited = (rateLimitResumeDate ?? .distantPast) > Date() + rateLimitResumeDate = Date().addingTimeInterval(retryAfter ?? Self.defaultRetryAfter) + Self.logger.error("ReaderAPIAccountDelegate: rate limited — pausing syncing until \(self.rateLimitResumeDate ?? .distantPast)") + + if !alreadyRateLimited { + postSyncError(WebserviceError.tooManyRequests(retryAfter: retryAfter), account: account, operation: operation) + } + } + + private func isTooManyRequests(_ error: Error) -> Bool { + if case WebserviceError.tooManyRequests = error { + return true + } + return false + } + + /// True when the reported Zone 1 (read) usage is close enough to the daily limit + /// that the full status downloads should be skipped until the limits reset. + private func shouldSkipStatusDownloadsToConserveQuota() -> Bool { + guard let usageLimits = caller.usageLimits else { + return false + } + guard usageLimits.resetDate > Date() else { + return false + } + guard Double(usageLimits.zone1Usage) >= Double(usageLimits.zone1Limit) * Self.zone1UsageThreshold else { + return false + } + Self.logger.info("ReaderAPIAccountDelegate: skipping status downloads — Zone 1 API usage is \(usageLimits.zone1Usage) of \(usageLimits.zone1Limit)") + return true + } + func postSyncError(_ error: Error, account: Account, operation: String, fileName: String = #fileID, functionName: String = #function, lineNumber: Int = #line) { let errorLogUserInfo = ErrorLogUserInfoKey.userInfo(sourceName: account.nameForDisplay, sourceID: account.type.rawValue, operation: operation, errorMessage: AccountError.detailedErrorMessage(error), fileName: fileName, functionName: functionName, lineNumber: lineNumber) NotificationCenter.default.post(name: .appDidEncounterError, object: self, userInfo: errorLogUserInfo) diff --git a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift index e36274f88..be3cb86ab 100644 --- a/Modules/Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift +++ b/Modules/Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift @@ -16,6 +16,14 @@ enum CreateReaderAPISubscriptionResult { case notFound } +/// Inoreader’s per-zone API usage, reported on every response. Zone 1 is reads. +/// +struct ReaderAPIUsageLimits { + let zone1Usage: Int + let zone1Limit: Int + let resetDate: Date +} + @MainActor final class ReaderAPICaller { enum ItemIDType { case unread @@ -33,6 +41,11 @@ enum CreateReaderAPISubscriptionResult { case readingList = "user/-/state/com.google/reading-list" } + private struct ConditionalGetKeys { + static let subscriptions = "subscriptions" + static let tags = "tags" + } + private enum ReaderAPIEndpoints: String { case login = "/accounts/ClientLogin" case token = "/reader/api/0/token" @@ -58,6 +71,9 @@ enum CreateReaderAPISubscriptionResult { var variant: ReaderAPIVariant = .generic var credentials: Credentials? + /// Most recent usage report. Nil for services that don’t send the headers. + private(set) var usageLimits: ReaderAPIUsageLimits? + @MainActor var server: String? { apiBaseURL?.host } @@ -192,10 +208,13 @@ enum CreateReaderAPISubscriptionResult { throw WebserviceError.noURL } - var request = URLRequest(url: callURL, readerAPICredentials: credentials) + let conditionalGet = accountSettings?.conditionalGetInfo(for: ConditionalGetKeys.tags) + var request = URLRequest(url: callURL, readerAPICredentials: credentials, conditionalGet: conditionalGet) addVariantHeaders(&request) - let (_, wrapper) = try await session.send(request: request, resultType: ReaderAPITagContainer.self) + // A 304 Not Modified comes back with an empty body, so this returns nil — callers skip syncing. + let (response, wrapper) = try await session.send(request: request, resultType: ReaderAPITagContainer.self) + storeConditionalGet(key: ConditionalGetKeys.tags, headers: response.allHeaderFields) return wrapper?.tags } @@ -257,11 +276,14 @@ enum CreateReaderAPISubscriptionResult { throw WebserviceError.noURL } - var request = URLRequest(url: callURL, readerAPICredentials: credentials) + let conditionalGet = accountSettings?.conditionalGetInfo(for: ConditionalGetKeys.subscriptions) + var request = URLRequest(url: callURL, readerAPICredentials: credentials, conditionalGet: conditionalGet) addVariantHeaders(&request) do { - let (_, container) = try await session.send(request: request, resultType: ReaderAPISubscriptionContainer.self) + // A 304 Not Modified comes back with an empty body, so this returns nil — callers skip syncing. + let (response, container) = try await session.send(request: request, resultType: ReaderAPISubscriptionContainer.self) + storeConditionalGet(key: ConditionalGetKeys.subscriptions, headers: response.allHeaderFields) return container?.subscriptions } catch { logger.error("ReaderAPICaller: retrieveSubscriptions — error calling API: \(error.localizedDescription)") @@ -417,7 +439,8 @@ enum CreateReaderAPISubscriptionResult { let entryWrapper = try await withWriteToken(endpoint: baseURL) { token -> ReaderAPIEntryWrapper? in let postData = Data("T=\(token)&output=json&\(idsToFetch)".utf8) - let (_, wrapper) = try await session.send(request: request, method: HTTPMethod.post, data: postData, resultType: ReaderAPIEntryWrapper.self) + let (response, wrapper) = try await session.send(request: request, method: HTTPMethod.post, data: postData, resultType: ReaderAPIEntryWrapper.self) + noteUsageLimits(from: response) return wrapper } @@ -478,6 +501,7 @@ enum CreateReaderAPISubscriptionResult { addVariantHeaders(&request) let (response, entries) = try await session.send(request: request, resultType: ReaderAPIReferenceWrapper.self) + noteUsageLimits(from: response) guard let entriesItemRefs = entries?.itemRefs, entriesItemRefs.count > 0 else { return [String]() @@ -515,7 +539,8 @@ enum CreateReaderAPISubscriptionResult { var request: URLRequest = URLRequest(url: callURL, readerAPICredentials: credentials) addVariantHeaders(&request) - let (_, entries) = try await self.session.send(request: request, resultType: ReaderAPIReferenceWrapper.self) + let (response, entries) = try await self.session.send(request: request, resultType: ReaderAPIReferenceWrapper.self) + noteUsageLimits(from: response) guard let entriesItemRefs = entries?.itemRefs, entriesItemRefs.count > 0 else { return try await retrieveItemIDs(type: type, url: callURL, dateInfo: dateInfo, itemIDs: itemIDs, continuation: entries?.continuation, pageHandler: pageHandler) @@ -605,10 +630,32 @@ private extension ReaderAPICaller { try await withWriteToken(endpoint: baseURL) { token in let postData = Data("T=\(token)&\(idsToFetch)&\(actionIndicator)=\(state.rawValue)".utf8) - _ = try await session.send(request: request, method: HTTPMethod.post, payload: postData) + let (response, _) = try await session.send(request: request, method: HTTPMethod.post, payload: postData) + noteUsageLimits(from: response) } } + private enum UsageLimitHeader { + static let zone1Usage = "X-Reader-Zone1-Usage" + static let zone1Limit = "X-Reader-Zone1-Limit" + static let resetAfter = "X-Reader-Limits-Reset-After" + } + + private static let defaultUsageLimitsResetAfter: TimeInterval = 60 * 60 * 24 + + private func storeConditionalGet(key: String, headers: [AnyHashable: Any]) { + accountSettings?.setConditionalGetInfo(HTTPConditionalGetInfo(headers: headers), for: key) + } + + private func noteUsageLimits(from response: HTTPURLResponse) { + guard let usageValue = response.value(forHTTPHeaderField: UsageLimitHeader.zone1Usage), let usage = Int(usageValue), + let limitValue = response.value(forHTTPHeaderField: UsageLimitHeader.zone1Limit), let limit = Int(limitValue), limit > 0 else { + return + } + let resetAfter = response.value(forHTTPHeaderField: UsageLimitHeader.resetAfter).flatMap { TimeInterval($0) } ?? Self.defaultUsageLimitsResetAfter + usageLimits = ReaderAPIUsageLimits(zone1Usage: usage, zone1Limit: limit, resetDate: Date().addingTimeInterval(resetAfter)) + } + /// Long-form item parameter for an articleID — i=tag:google.com,2005:reader/item/000000000004c608. /// The long form is zero-padded 16-digit hex, two’s-complement for negative IDs. /// Returns nil for an articleID that can’t be encoded for this server. diff --git a/Modules/RSWeb/Sources/RSWeb/WebServices/URLSession+Webservice.swift b/Modules/RSWeb/Sources/RSWeb/WebServices/URLSession+Webservice.swift index 612867c53..9c49b9b72 100644 --- a/Modules/RSWeb/Sources/RSWeb/WebServices/URLSession+Webservice.swift +++ b/Modules/RSWeb/Sources/RSWeb/WebServices/URLSession+Webservice.swift @@ -14,6 +14,7 @@ public enum WebserviceError: LocalizedError, Sendable { case noURL case suspended case httpError(status: Int) + case tooManyRequests(retryAfter: TimeInterval?) public var errorDescription: String? { switch self { @@ -25,6 +26,8 @@ public enum WebserviceError: LocalizedError, Sendable { return NSLocalizedString("The URL for the request is missing.", comment: "No URL") case .suspended: return NSLocalizedString("The request was not sent because syncing is suspended.", comment: "Suspended") + case .tooManyRequests: + return NSLocalizedString("The server reported too many requests. Syncing is paused temporarily.", comment: "Too many requests") } } @@ -100,6 +103,12 @@ nonisolated extension URLSession { switch httpResponse.forcedStatusCode { case 200...399: return httpResponse + case HTTPResponseCode.tooManyRequests: + var retryAfter: TimeInterval? + if let headerValue = httpResponse.value(forHTTPHeaderField: HTTPResponseHeader.retryAfter) { + retryAfter = TimeInterval(headerValue) + } + throw WebserviceError.tooManyRequests(retryAfter: retryAfter) default: throw WebserviceError.httpError(status: httpResponse.forcedStatusCode) }