diff --git a/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift b/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift index a531eabb8..98a090159 100644 --- a/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift +++ b/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift @@ -42,8 +42,8 @@ extension Notification.Name { /// by `discoverThumbnailURLs(for:)`, and the results are saved in `ImageMetadataDatabase`, /// so each article’s HTML is parsed once. /// -/// URLs that recently failed to download are skipped, so a dead or rejected image -/// falls through to the next source. +/// URLs that recently failed to download, and images too small, too narrow, or unreadable +/// to be thumbnails, are skipped, so they fall through to the next source. /// /// Images are decoded at display size from `DownloadedImageCache`’s copy, off the main thread. @MainActor public final class ArticleThumbnailFinder { @@ -64,6 +64,7 @@ extension Notification.Name { private var articleIDsBeingDiscovered = Set() private let imageCache = NSCache() // See cacheKey private var cacheKeysInProgress = Set() + private var urlsThatFailedToDecode = Set() // So a failure notification can’t lead to the same attempt again /// Decoded bitmaps: about 1 MB each in small mode, 2–5 MB in large mode. private static let imageCacheByteLimit = 128 * 1024 * 1024 @@ -191,8 +192,8 @@ private extension ArticleThumbnailFinder { imageCache.setObject(decodedImage.image, forKey: cacheKey, cost: decodedImage.byteCount) NotificationCenter.default.post(name: .articleThumbnailDidBecomeAvailable, object: self, userInfo: [Self.urlKey: url]) } catch { - if error.rejectedPixelSize != nil { - metadataDatabase.recordInsignificantDimensions(url: url) + if error.decodingFailed || error.rejectedPixelSize != nil { + urlsThatFailedToDecode.insert(url) } if !error.isTransient { NotificationCenter.default.post(name: .articleThumbnailDownloadDidFail, object: self, userInfo: [Self.urlKey: url]) @@ -222,7 +223,7 @@ private extension ArticleThumbnailFinder { } func isUsable(_ urlString: String) -> Bool { - SignificantImageFilter.isSignificant(urlString: urlString, width: nil, height: nil) && !metadataDatabase.recentlyFailed(url: urlString) && !metadataDatabase.recentlyLackedSignificantDimensions(url: urlString) + SignificantImageFilter.isSignificant(urlString: urlString, width: nil, height: nil) && !metadataDatabase.recentlyFailed(url: urlString) && !metadataDatabase.isUnsuitableForThumbnail(url: urlString) && !urlsThatFailedToDecode.contains(urlString) } func needsHTMLDiscovery(_ article: Article) -> Bool { diff --git a/Modules/Images/Sources/Images/DownloadedImageCache.swift b/Modules/Images/Sources/Images/DownloadedImageCache.swift index 4331c1663..72f802a4b 100644 --- a/Modules/Images/Sources/Images/DownloadedImageCache.swift +++ b/Modules/Images/Sources/Images/DownloadedImageCache.swift @@ -117,11 +117,17 @@ private extension DownloadedImageCache { throw ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: true) } - let statusCode = (downloadResponse.response as? HTTPURLResponse)?.statusCode + let httpResponse = downloadResponse.response as? HTTPURLResponse + let statusCode = httpResponse?.statusCode if let data = downloadResponse.data, !data.isEmpty, let response = downloadResponse.response, response.statusIsOK { - let storedData = await Self.scaledImageData(data) - await Self.saveToDisk(diskCache, key: Self.diskKey(url), data: storedData) - return (storedData, downloadResponse) + let storedImage = await Self.storedImage(data) + await Self.saveToDisk(diskCache, key: Self.diskKey(url), data: storedImage.data) + var conditionalGetInfo: HTTPConditionalGetInfo? + if let httpResponse { + conditionalGetInfo = HTTPConditionalGetInfo(urlResponse: httpResponse) + } + ImageMetadataDatabase.shared.saveDownloadedImage(DownloadedImageRecord(url: url, byteCount: storedImage.data.count, pixelSize: storedImage.pixelSize, conditionalGetInfo: conditionalGetInfo)) + return (storedImage.data, downloadResponse) } // 2xx with empty / missing body — server said OK but gave us no image bytes. @@ -140,8 +146,9 @@ private extension DownloadedImageCache { } /// Data that ImageIO can’t read, such as SVG, is kept as is, since `RSImage` may still read it. - @concurrent static func scaledImageData(_ data: Data) async -> Data { - RSImage.scaledImageData(data, maxPixelSize: maxPixelSize, format: .jpeg(compressionQuality: compressionQuality)) ?? data + @concurrent static func storedImage(_ data: Data) async -> (data: Data, pixelSize: (width: Int, height: Int)?) { + let storedData = RSImage.scaledImageData(data, maxPixelSize: maxPixelSize, format: .jpeg(compressionQuality: compressionQuality)) ?? data + return (data: storedData, pixelSize: RSImage.largestFramePixelSize(storedData)) } @concurrent static func readFromDisk(_ diskCache: BinaryDiskCache, key: String) async -> Data? { diff --git a/Modules/Images/Sources/Images/DownloadedImageTable.swift b/Modules/Images/Sources/Images/DownloadedImageTable.swift new file mode 100644 index 000000000..e89e6f53e --- /dev/null +++ b/Modules/Images/Sources/Images/DownloadedImageTable.swift @@ -0,0 +1,70 @@ +// +// DownloadedImageTable.swift +// Images +// +// Created by Brent Simmons on 10/26/26. +// + +import Foundation +import RSWeb +import RSDatabase +import RSDatabaseObjC + +/// A copy stored by `DownloadedImageCache`. `pixelSize` is nil when ImageIO can’t read the image. +struct DownloadedImageRecord: Sendable { + let url: String + let byteCount: Int + let pixelSize: (width: Int, height: Int)? + let conditionalGetInfo: HTTPConditionalGetInfo? +} + +/// One row per copy stored by `DownloadedImageCache`. +struct DownloadedImageTable { + + static let name = "downloadedImage" + + private struct Column { + static let url = "url" + static let byteCount = "byteCount" + static let pixelWidth = "pixelWidth" + static let pixelHeight = "pixelHeight" + static let lastAccessed = "lastAccessed" + static let etag = "etag" + static let lastModified = "lastModified" + } + + /// Every row’s URL and pixel size. `pixelSize` is nil when ImageIO couldn’t read the image. + static func fetchPixelSizes(database: FMDatabase) -> [(url: String, pixelSize: (width: Int, height: Int)?)] { + var results = [(url: String, pixelSize: (width: Int, height: Int)?)]() + guard let resultSet = database.executeQuery("SELECT \(Column.url), \(Column.pixelWidth), \(Column.pixelHeight) FROM \(name);", withArgumentsIn: []) else { + return results + } + defer { + resultSet.close() + } + while resultSet.next() { + guard let url = resultSet.string(forColumn: Column.url) else { + continue + } + var pixelSize: (width: Int, height: Int)? + if !resultSet.columnIsNull(Column.pixelWidth) && !resultSet.columnIsNull(Column.pixelHeight) { + pixelSize = (width: resultSet.long(forColumn: Column.pixelWidth), height: resultSet.long(forColumn: Column.pixelHeight)) + } + results.append((url: url, pixelSize: pixelSize)) + } + return results + } + + static func save(_ record: DownloadedImageRecord, database: FMDatabase) { + let dictionary: DatabaseDictionary = [ + Column.url: record.url, + Column.byteCount: record.byteCount, + Column.pixelWidth: record.pixelSize?.width as Any, + Column.pixelHeight: record.pixelSize?.height as Any, + Column.lastAccessed: Date().timeIntervalSince1970, + Column.etag: record.conditionalGetInfo?.etag as Any, + Column.lastModified: record.conditionalGetInfo?.lastModified as Any + ] + database.insertRow(dictionary, insertType: .orReplace, tableName: name) + } +} diff --git a/Modules/Images/Sources/Images/ImageMetadataDatabase.swift b/Modules/Images/Sources/Images/ImageMetadataDatabase.swift index 5525a9ec9..1f6f3d52e 100644 --- a/Modules/Images/Sources/Images/ImageMetadataDatabase.swift +++ b/Modules/Images/Sources/Images/ImageMetadataDatabase.swift @@ -10,8 +10,9 @@ import os import RSCore import RSDatabase import RSDatabaseObjC +import RSParser -/// Per-URL image metadata: discovered URLs and failure tracking. +/// Per-URL image metadata: discovered URLs, failure tracking, and the copies `DownloadedImageCache` stores. /// Also thumbnails found in article HTML, which aren’t loaded into memory at init, since there’s a row per article. @MainActor public final class ImageMetadataDatabase { @@ -19,7 +20,6 @@ import RSDatabaseObjC public static let failureRetryDays = 5 private static let failureRetentionDays = 33 - private static let insignificantDimensionsKeyPrefix = "insignificantDimensions:" // Can’t collide with an http(s) URL public let databasePath: String @@ -31,12 +31,14 @@ import RSDatabaseObjC private var homePagesWithNoFavicon = Set() private var feedURLToIconURL = [String: String]() private var failureDates = [String: Date]() + private var urlsUnsuitableForThumbnails = Set() private static let tableCreationStatements = """ CREATE TABLE IF NOT EXISTS downloadFailure (url TEXT PRIMARY KEY NOT NULL, statusCode INTEGER, lastChecked REAL NOT NULL); CREATE TABLE IF NOT EXISTS homePageFavicon (homePageURL TEXT PRIMARY KEY NOT NULL, faviconURL TEXT, lastChecked REAL NOT NULL); CREATE TABLE IF NOT EXISTS feedIconURL (feedURL TEXT PRIMARY KEY NOT NULL, iconURL TEXT NOT NULL, lastChecked REAL NOT NULL); CREATE TABLE IF NOT EXISTS articleThumbnail (articleID TEXT PRIMARY KEY NOT NULL, thumbnailURL TEXT, lastChecked REAL NOT NULL); + CREATE TABLE IF NOT EXISTS downloadedImage (url TEXT PRIMARY KEY NOT NULL, byteCount INTEGER NOT NULL, pixelWidth INTEGER, pixelHeight INTEGER, lastAccessed REAL NOT NULL, etag TEXT, lastModified TEXT); """ private convenience init() { @@ -143,36 +145,44 @@ import RSDatabaseObjC } } - // MARK: - Insignificant Dimensions + // MARK: - DownloadedImage - // An image too small or too narrow to be a thumbnail may still be a fine feed icon, - // so these are kept apart from failures, which every downloader honors. - - public func recentlyLackedSignificantDimensions(url: String) -> Bool { - recentlyFailed(url: Self.insignificantDimensionsKey(url)) + /// True when 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) } - public func recordInsignificantDimensions(url: String) { - recordFailure(url: Self.insignificantDimensionsKey(url), statusCode: nil) + func saveDownloadedImage(_ record: DownloadedImageRecord) { + if Self.isSuitableForThumbnail(record.pixelSize) { + urlsUnsuitableForThumbnails.remove(record.url) + } else { + urlsUnsuitableForThumbnails.insert(record.url) + } + queue.runInDatabase { database in + DownloadedImageTable.save(record, database: database) + } } } private extension ImageMetadataDatabase { - static func insignificantDimensionsKey(_ url: String) -> String { - insignificantDimensionsKeyPrefix + url + static func isSuitableForThumbnail(_ pixelSize: (width: Int, height: Int)?) -> Bool { + guard let pixelSize else { + return false + } + return SignificantImageFilter.hasSignificantDimensions(width: pixelSize.width, height: pixelSize.height) } -} - -private extension ImageMetadataDatabase { func loadCachesFromDatabase() { nonisolated(unsafe) var homePageRecords = [HomePageFaviconRecord]() nonisolated(unsafe) var feedIcons = [String: String]() nonisolated(unsafe) var failures = [String: Date]() + nonisolated(unsafe) var pixelSizes = [(url: String, pixelSize: (width: Int, height: Int)?)]() nonisolated(unsafe) var homePageDuration: TimeInterval = 0 nonisolated(unsafe) var feedIconDuration: TimeInterval = 0 nonisolated(unsafe) var failureDuration: TimeInterval = 0 + nonisolated(unsafe) var pixelSizeDuration: TimeInterval = 0 let totalStart = Date() queue.runInDatabaseSync { database in @@ -187,6 +197,10 @@ private extension ImageMetadataDatabase { stepStart = Date() failures = DownloadFailureTable.fetchAll(database: database) failureDuration = Date().timeIntervalSince(stepStart) + + stepStart = Date() + pixelSizes = DownloadedImageTable.fetchPixelSizes(database: database) + pixelSizeDuration = Date().timeIntervalSince(stepStart) } let totalDuration = Date().timeIntervalSince(totalStart) @@ -200,7 +214,8 @@ private extension ImageMetadataDatabase { } feedURLToIconURL = feedIcons failureDates = failures + urlsUnsuitableForThumbnails = Set(pixelSizes.filter { !Self.isSuitableForThumbnail($0.pixelSize) }.map(\.url)) - Self.logger.info("Initial fetches: homePageFavicon \(homePageRecords.count) rows in \(homePageDuration) seconds, feedIconURL \(feedIcons.count) rows in \(feedIconDuration) seconds, downloadFailure \(failures.count) rows in \(failureDuration) seconds, total \(totalDuration) seconds") + Self.logger.info("Initial fetches: homePageFavicon \(homePageRecords.count) rows in \(homePageDuration) seconds, feedIconURL \(feedIcons.count) rows in \(feedIconDuration) seconds, downloadFailure \(failures.count) rows in \(failureDuration) seconds, downloadedImage \(pixelSizes.count) rows in \(pixelSizeDuration) seconds, total \(totalDuration) seconds") } } diff --git a/Modules/Images/Tests/ImagesTests/ArticleThumbnailFinderTests.swift b/Modules/Images/Tests/ImagesTests/ArticleThumbnailFinderTests.swift index ab6ad9e11..ac3aa459b 100644 --- a/Modules/Images/Tests/ImagesTests/ArticleThumbnailFinderTests.swift +++ b/Modules/Images/Tests/ImagesTests/ArticleThumbnailFinderTests.swift @@ -42,7 +42,7 @@ private typealias ArticleAttachment = Articles.Attachment let finder = ArticleThumbnailFinder(metadataDatabase: metadataDatabase) let article = makeArticle(imageURL: "https://example.com/image.jpg", thumbnailURL: "https://example.com/logo.png") - metadataDatabase.recordInsignificantDimensions(url: "https://example.com/logo.png") + metadataDatabase.saveDownloadedImage(DownloadedImageRecord(url: "https://example.com/logo.png", byteCount: 1024, pixelSize: (width: 48, height: 48), conditionalGetInfo: nil)) #expect(finder.thumbnailURL(for: article, mode: .small) == "https://example.com/image.jpg") #expect(!metadataDatabase.recentlyFailed(url: "https://example.com/logo.png"))