Cache responses for just over 10 minutes, so that feeds can’t be refreshed too often. Be kind to feed publishers! Fix #4700.

This commit is contained in:
Brent Simmons committed 2025-10-16 14:14:03 -07:00
1 parent 502b23b9fe
commit a16cda2665
1 file changed
+52 -5
@@ -8,6 +8,7 @@
import Foundation
import os
import RSCore
// Create a DownloadSessionDelegate, then create a DownloadSession.
// To download things: call download with a set of URLs. DownloadSession will call the various delegate methods.
@@ -30,6 +31,19 @@ struct HTTP4xxResponse {
}
}
struct DownloadCacheRecord: CacheRecord {
let dateCreated = Date()
let data: Data
let response: URLResponse?
let error: NSError?
init(data: Data, response: URLResponse?, error: NSError?) {
self.data = data
self.response = response
self.error = error
}
}
@objc public final class DownloadSession: NSObject {
public let downloadProgress = DownloadProgress(numberOfTasks: 0)
@@ -43,6 +57,12 @@ struct HTTP4xxResponse {
private var redirectCache = [URL: URL]()
private var queue = [URL]()
// Static so that it can be shared by all instances of DownloadSession.
// A feed might appear in both an On My Mac and iCloud account, for instance.
// Cache items live for 13 minutes, in order to ensure no feed is downloaded more often
// than 10 minutes (plus a little extra).
private static let responseCache = Cache<DownloadCacheRecord>(timeToLive: 13 * 60, timeBetweenCleanups: 4 * 60)
// 429 Too Many Requests responses
private var retryAfterMessages = [String: HTTPResponse429]()
@@ -112,9 +132,20 @@ extension DownloadSession: URLSessionTaskDelegate {
}
guard let info = infoForTask(task) else {
if let url = task.originalRequest?.url {
Self.logger.debug("DownloadSession: no task info found for \(url)")
} else {
Self.logger.debug("DownloadSession: no task info found for unknown URL")
}
return
}
if let url = task.originalRequest?.url {
Self.logger.debug("DownloadSession: Caching response for \(url)")
let responseToCache = DownloadCacheRecord(data: info.data as Data, response: info.urlResponse, error: error as NSError?)
Self.responseCache[url.absoluteString] = responseToCache
}
delegate.downloadSession(self, downloadDidComplete: info.url, response: info.urlResponse, data: info.data as Data, error: error as NSError?)
}
@@ -156,13 +187,21 @@ extension DownloadSession: URLSessionDataDelegate {
taskInfo.urlResponse = response
}
if !response.statusIsOK {
let statusCode = response.forcedStatusCode
if statusCode >= 400 {
if statusCode != HTTPResponseCode.tooManyRequests {
if let urlString = response.url?.absoluteString {
Self.logger.debug("DownloadSession: Caching >= 400 response for \(urlString)")
let responseToCache = DownloadCacheRecord(data: Data(), response: response, error: nil)
Self.responseCache[urlString] = responseToCache
}
}
Self.logger.debug("DownloadSession: canceling task due to >= 400 response \(response)")
completionHandler(.cancel)
removeTask(dataTask)
let statusCode = response.forcedStatusCode
if statusCode == HTTPResponseCode.tooManyRequests {
handle429Response(dataTask, response)
} else if (400...499).contains(statusCode), let url = response.url {
@@ -205,11 +244,18 @@ private extension DownloadSession {
let urlToUse = cachedRedirect(for: url) ?? url
if requestShouldBeDroppedDueToActive429(urlToUse) {
Self.logger.info("Dropping request for previous 429: \(urlToUse)")
Self.logger.info("DownloadSession: Dropping request for previous 429: \(urlToUse)")
return
}
if requestShouldBeDroppedDueToPrevious400(urlToUse) {
Self.logger.info("Dropping request for previous 400-499: \(urlToUse)")
Self.logger.info("DownloadSession: Dropping request for previous 400-499: \(urlToUse)")
return
}
// Check cache
if let cachedResponse = Self.responseCache[urlToUse.absoluteString] {
Self.logger.info("DownloadSession: using cached response for \(urlToUse) - \(cachedResponse.response?.forcedStatusCode ?? -1)")
delegate.downloadSession(self, downloadDidComplete: url, response: cachedResponse.response, data: cachedResponse.data, error: cachedResponse.error)
return
}
@@ -224,6 +270,7 @@ private extension DownloadSession {
return request
}()
Self.logger.debug("DownloadSession: adding dataTask for \(urlToUse)")
let task = urlSession.dataTask(with: urlRequest)
let info = DownloadInfo(url)