Stop an image too large for the timeline from blocking it as an icon. Save new conditional GET info when a check finds the image unchanged.

This commit is contained in:
Brent Simmons committed 2026-11-03 16:09:13 -08:00
1 parent d49c25abf9
commit b24d552c81
4 files changed
+60 -8

No files matched your search

@@ -291,7 +291,10 @@ private extension DownloadedImageCache {
}
activityLog.didFail(activityOwner, kind: activityKind, error: error)
}
if !error.isTransient {
if error.rejectedByteCount != nil {
// Too large only for the timeline, so icons and the article view can still use it.
ImageDatabase.shared.saveUnsuitableForThumbnail(url: url)
} else if !error.isTransient {
ImageDatabase.shared.recordFailure(url: url)
}
return .failure(error)
@@ -396,9 +399,10 @@ private extension DownloadedImageCache {
}
let httpResponse = downloadResponse.response as? HTTPURLResponse
var isUnchanged = httpResponse?.statusCode == HTTPResponseCode.notModified
if let data = downloadResponse.data, !data.isEmpty, let httpResponse, httpResponse.statusIsOK {
// A server without validators sends the whole image even when it hasn’t changed.
let isUnchanged = await isStoredImage(data, url: url)
isUnchanged = await isStoredImage(data, url: url)
if !isUnchanged, (try? await saveImage(data, url: url, httpResponse: httpResponse, isIcon: true)) == true {
Self.logger.info("Replaced changed image at \(url)")
await Self.deleteFromDisk(diskCache, keys: [Self.derivedDiskKey(url, suffix: Self.scaledIconSuffix)])
@@ -412,8 +416,15 @@ private extension DownloadedImageCache {
noteDownloadResult(.failure(error), url: url)
}
// The server may send a new ETag or Last-Modified with an unchanged image, so later checks can get a 304.
var newConditionalGetInfo: HTTPConditionalGetInfo?
if isUnchanged, let httpResponse {
newConditionalGetInfo = HTTPConditionalGetInfo(urlResponse: httpResponse)
}
// 304 Not Modified, the same bytes, an error response, not an image, or a failed write: keep the copy and check again later.
ImageDatabase.shared.saveDownloadedImageNextCheck(url: url, nextCheck: Self.nextCheck(httpResponse, hasValidators: validation.conditionalGetInfo != nil))
let nextCheck = Self.nextCheck(httpResponse, hasValidators: newConditionalGetInfo != nil || validation.conditionalGetInfo != nil)
ImageDatabase.shared.saveDownloadedImageNextCheck(url: url, nextCheck: nextCheck, conditionalGetInfo: newConditionalGetInfo)
}
/// Compares with the original, or, when only the scaled icon is kept, with that. Scaling the same bytes gives the same result.
@@ -109,8 +109,17 @@ struct DownloadedImageTable {
return DownloadedImageValidation(nextCheck: nextCheck, conditionalGetInfo: conditionalGetInfo)
}
static func saveNextCheck(url: String, nextCheck: Date, database: FMDatabase) {
database.updateRowsWithValue(nextCheck.timeIntervalSince1970, valueKey: Column.nextCheck, whereKey: Column.url, equals: url, tableName: name)
static func saveNextCheck(url: String, nextCheck: Date, conditionalGetInfo: HTTPConditionalGetInfo?, database: FMDatabase) {
guard let conditionalGetInfo else {
database.updateRowsWithValue(nextCheck.timeIntervalSince1970, valueKey: Column.nextCheck, whereKey: Column.url, equals: url, tableName: name)
return
}
let dictionary: DatabaseDictionary = [
Column.nextCheck: nextCheck.timeIntervalSince1970,
Column.etag: conditionalGetInfo.etag as Any,
Column.lastModified: conditionalGetInfo.lastModified as Any
]
database.updateRowsWithDictionary(dictionary, whereKey: Column.url, equals: url, tableName: name)
}
static func saveAccessDate(url: String, database: FMDatabase) {
@@ -11,6 +11,7 @@ import RSCore
import RSDatabase
import RSDatabaseObjC
import RSParser
import RSWeb
/// Per-URL image metadata: discovered URLs, failure tracking, and the copies `DownloadedImageCache` stores.
@MainActor public final class ImageDatabase {
@@ -169,12 +170,17 @@ import RSParser
// MARK: - DownloadedImage
/// True when the stored copy is too small, too narrow, or unreadable by ImageIO.
/// True when the image is too large to download for the timeline, or the stored copy is too small, too narrow, or unreadable by ImageIO.
/// It may still be a fine feed icon.
public func isUnsuitableForThumbnail(url: String) -> Bool {
urlsUnsuitableForThumbnails.contains(url)
}
/// For this session.
func saveUnsuitableForThumbnail(url: String) {
urlsUnsuitableForThumbnails.insert(url)
}
func saveDownloadedImage(_ record: DownloadedImageRecord) {
if Self.isSuitableForThumbnail(record.pixelSize) {
urlsUnsuitableForThumbnails.remove(record.url)
@@ -206,9 +212,10 @@ import RSParser
}
}
func saveDownloadedImageNextCheck(url: String, nextCheck: Date) {
/// Saves `conditionalGetInfo` too when it’s not nil. Otherwise the saved validators are kept.
func saveDownloadedImageNextCheck(url: String, nextCheck: Date, conditionalGetInfo: HTTPConditionalGetInfo?) {
queue.runInDatabase { database in
DownloadedImageTable.saveNextCheck(url: url, nextCheck: nextCheck, database: database)
DownloadedImageTable.saveNextCheck(url: url, nextCheck: nextCheck, conditionalGetInfo: conditionalGetInfo, database: database)
}
}
@@ -111,6 +111,31 @@ import RSWeb
// Waits for the cleanup init queues, which would otherwise run after the folder is deleted.
await reopenedImageDatabase.vacuum()
}
@Test func newValidatorsAreSavedWithNextCheck() async throws {
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("ImageDatabaseTests-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
defer {
try? FileManager.default.removeItem(at: folder)
}
let databasePath = folder.appendingPathComponent("Images.db").path
let iconURL = "https://example.com/apple-touch-icon.png"
let oldConditionalGetInfo = try #require(HTTPConditionalGetInfo(lastModified: nil, etag: "\"old\""))
let newConditionalGetInfo = try #require(HTTPConditionalGetInfo(lastModified: "Tue, 03 Nov 2026 12:00:00 GMT", etag: "\"new\""))
let nextCheck = Date(timeIntervalSince1970: 2_000_000_000)
let laterNextCheck = Date(timeIntervalSince1970: 2_100_000_000)
let imageDatabase = ImageDatabase(databasePath: databasePath)
imageDatabase.saveDownloadedImage(DownloadedImageRecord(url: iconURL, pixelSize: (width: 180, height: 180), conditionalGetInfo: oldConditionalGetInfo, nextCheck: nextCheck, isIcon: true))
imageDatabase.saveDownloadedImageNextCheck(url: iconURL, nextCheck: laterNextCheck, conditionalGetInfo: newConditionalGetInfo)
let validation = await imageDatabase.fetchDownloadedImageValidation(url: iconURL)
#expect(validation?.conditionalGetInfo == newConditionalGetInfo)
#expect(validation?.nextCheck == laterNextCheck)
// Waits for the cleanup init queues, which would otherwise run after the folder is deleted.
await imageDatabase.vacuum()
}
}
private extension ImageDatabaseTests {