diff --git a/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift b/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift index 34fe4ecfb..0247b3821 100644 --- a/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift +++ b/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift @@ -40,7 +40,7 @@ extension Notification.Name { /// before the provided thumbnail, which is usually too small to fill the timeline’s width. /// /// The first three sources are property reads. The HTML is parsed by `findThumbnailURLs(for:)`, -/// and the results are saved in `ImageDatabase`, so each article’s HTML is parsed once. +/// and the results are cached in memory, so each article’s HTML is parsed once per launch. /// /// 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. @@ -84,13 +84,13 @@ extension Notification.Name { #else private static let largeThumbnailMaxPixelHeight = 540 #endif - /// HTML images saved per article, so one that fails or is too small falls through to the next. + /// HTML images kept per article, so one that fails or is too small falls through to the next. nonisolated private static let maxHTMLThumbnailURLsPerArticle = 3 - /// Articles parsed and saved at a time, which also limits how long a save holds the database queue. + /// Articles parsed at a time off the main thread. static let parsingBatchSize = 100 /// Takes about 0.04 seconds on an M1 Max. static let maximumArticlesParsedBeforeReturning = 1000 - /// Entries in htmlThumbnailURLs, a few hundred bytes each. Past this, it’s emptied, and the next discovery reloads its articles from the database. + /// Entries in htmlThumbnailURLs, a few hundred bytes each. Past this, it’s emptied, and the next discovery parses its articles again. private static let maxCachedArticleCount = 50_000 /// Entries per mode in chosenThumbnailURLs. Past this, that mode’s entries are emptied. private static let maxChosenThumbnailURLCount = 50_000 @@ -147,8 +147,7 @@ extension Notification.Name { } /// Looks for thumbnails in the HTML of articles that have no usable provided image. - /// Results saved in the database, and the first articles’ parsed results, are ready when this returns, so that rows laid out next can use them. - /// This blocks while the database answers and those articles are parsed. + /// The first articles are parsed before this returns, so that rows laid out next can use the results. /// The rest are parsed off the main thread in batches, in the order given. /// `.articleThumbnailURLsDidBecomeAvailable` is posted after this returns, for those that have thumbnails: once for the first articles, then after each batch. /// The returned task finishes after the last batch. @@ -157,12 +156,7 @@ extension Notification.Name { htmlThumbnailURLs.removeAll() } - let articlesToFind = articles.filter(needsHTMLDiscovery) - if !articlesToFind.isEmpty { - cacheRecords(imageDatabase.fetchArticleThumbnailsSync(articleIDs: articlesToFind.map(\.articleID))) - } - - let articleHTMLs = articlesToFind.filter { !isCached($0.articleID) }.compactMap(ArticleHTML.init) + let articleHTMLs = articles.filter(needsHTMLDiscovery).compactMap(ArticleHTML.init) let recordsParsedBeforeReturning = Self.thumbnailRecords(Array(articleHTMLs.prefix(Self.maximumArticlesParsedBeforeReturning))) cacheRecords(recordsParsedBeforeReturning) @@ -175,17 +169,12 @@ extension Notification.Name { articleIDsBeingDiscovered.subtract(articleIDsToParseLater) } - for batchStart in stride(from: 0, to: recordsParsedBeforeReturning.count, by: Self.parsingBatchSize) { - let batchEnd = min(batchStart + Self.parsingBatchSize, recordsParsedBeforeReturning.count) - imageDatabase.saveArticleThumbnails(Array(recordsParsedBeforeReturning[batchStart.. [ArticleThumbnailRecord] { - var results = [ArticleThumbnailRecord]() - for articleIDsChunk in articleIDs.chunked(into: maximumArticleIDsPerQuery) { - guard let resultSet = database.selectRowsWhere(key: Column.articleID, equalsAnyValue: articleIDsChunk, tableName: name) else { - continue - } - while resultSet.next() { - guard let articleID = resultSet.string(forColumn: Column.articleID) else { - continue - } - let thumbnailURLs = resultSet.string(forColumn: Column.thumbnailURLs)?.components(separatedBy: urlSeparator) ?? [] - results.append(ArticleThumbnailRecord(articleID: articleID, thumbnailURLs: thumbnailURLs)) - } - resultSet.close() - } - return results - } - - static func save(_ records: [ArticleThumbnailRecord], database: FMDatabase) { - let lastChecked = Date().timeIntervalSince1970 - for record in records { - let dictionary: DatabaseDictionary = [ - Column.articleID: record.articleID, - Column.thumbnailURLs: record.thumbnailURLs.isEmpty ? NSNull() : record.thumbnailURLs.joined(separator: urlSeparator), - Column.lastChecked: lastChecked - ] - database.insertRow(dictionary, insertType: .orReplace, tableName: name) - } - } - - /// Removes rows whose `lastChecked` predates the cutoff. Cutoff is Unix epoch seconds. - static func removeExpired(olderThan cutoff: TimeInterval, database: FMDatabase) { - let sql = "DELETE FROM \(name) WHERE \(Column.lastChecked) < ?;" - database.executeUpdate(sql, withArgumentsIn: [cutoff]) - } -} diff --git a/Modules/Images/Sources/Images/ImageDatabase.swift b/Modules/Images/Sources/Images/ImageDatabase.swift index 3a80071a4..a6792b22b 100644 --- a/Modules/Images/Sources/Images/ImageDatabase.swift +++ b/Modules/Images/Sources/Images/ImageDatabase.swift @@ -13,15 +13,12 @@ import RSDatabaseObjC import RSParser /// 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 ImageDatabase { public static let shared = ImageDatabase() public static let failureRetryDays = 5 private static let failureRetentionDays = 33 - /// After this, an article’s HTML is checked for thumbnails again, in case it changed. - private static let htmlThumbnailRetentionDays = 33 public let databasePath: String @@ -39,10 +36,12 @@ import RSParser 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 articleThumbnailURLs (articleID TEXT PRIMARY KEY NOT NULL, thumbnailURLs 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, nextCheck REAL NOT NULL); """ + /// Development builds created this table. + nonisolated private static let dropArticleThumbnailTableStatement = "DROP TABLE IF EXISTS articleThumbnailURLs;" + private static let databaseFileName = "Images.db" private static let legacyDatabaseFileName = "ImageMetadata.db" @@ -73,12 +72,10 @@ import RSParser loadCachesFromDatabase() - let now = Date().timeIntervalSince1970 - let failureCutoff = now - TimeInterval(days: Self.failureRetentionDays) - let htmlThumbnailCutoff = now - TimeInterval(days: Self.htmlThumbnailRetentionDays) + let failureCutoff = Date().timeIntervalSince1970 - TimeInterval(days: Self.failureRetentionDays) queue.runInDatabase { database in DownloadFailureTable.removeExpired(olderThan: failureCutoff, database: database) - ArticleThumbnailTable.removeExpired(olderThan: htmlThumbnailCutoff, database: database) + database.executeStatements(Self.dropArticleThumbnailTableStatement) database.checkpoint() } } @@ -126,22 +123,6 @@ import RSParser } } - // MARK: - ArticleThumbnail - - func fetchArticleThumbnailsSync(articleIDs: [String]) -> [ArticleThumbnailRecord] { - nonisolated(unsafe) var records = [ArticleThumbnailRecord]() - queue.runInDatabaseSync { database in - records = ArticleThumbnailTable.fetch(articleIDs: articleIDs, database: database) - } - return records - } - - func saveArticleThumbnails(_ records: [ArticleThumbnailRecord]) { - queue.runInTransaction { database in - ArticleThumbnailTable.save(records, database: database) - } - } - // MARK: - DownloadFailure public func recentlyFailed(url: String) -> Bool { diff --git a/Modules/Images/Tests/ImagesTests/ArticleThumbnailFinderTests.swift b/Modules/Images/Tests/ImagesTests/ArticleThumbnailFinderTests.swift index 62c5fce25..e8d0737c2 100644 --- a/Modules/Images/Tests/ImagesTests/ArticleThumbnailFinderTests.swift +++ b/Modules/Images/Tests/ImagesTests/ArticleThumbnailFinderTests.swift @@ -49,7 +49,7 @@ private typealias ArticleAttachment = Articles.Attachment #expect(!imageDatabase.recentlyFailed(url: "https://example.com/logo.png")) } - @Test func htmlThumbnailIsDiscoveredAndSaved() async { + @Test func htmlThumbnailIsDiscovered() async { let imageDatabase = ImageDatabase(databasePath: ":memory:") let finder = ArticleThumbnailFinder(imageDatabase: imageDatabase) let html = """ @@ -66,11 +66,6 @@ private typealias ArticleAttachment = Articles.Attachment #expect(finder.thumbnailURL(for: articleWithImage, mode: .small) == "https://example.com/uploads/photo.jpg") #expect(finder.thumbnailURL(for: articleWithoutImage, mode: .small) == nil) - let records = imageDatabase.fetchArticleThumbnailsSync(articleIDs: ["1", "2"]) - #expect(Set(records.map(\.articleID)) == ["1", "2"]) - #expect(records.first { $0.articleID == "1" }?.thumbnailURLs == ["https://example.com/uploads/photo.jpg", "https://example.com/uploads/second-photo.jpg"]) - #expect(records.first { $0.articleID == "2" }?.thumbnailURLs == []) - imageDatabase.recordFailure(url: "https://example.com/uploads/photo.jpg", statusCode: 404) finder.thumbnailURLDidFail("https://example.com/uploads/photo.jpg") #expect(finder.thumbnailURL(for: articleWithImage, mode: .small) == "https://example.com/uploads/second-photo.jpg") @@ -84,7 +79,6 @@ private typealias ArticleAttachment = Articles.Attachment // The HTML isn’t parsed while the provided image is usable. await finder.findThumbnailURLs(for: [article]).value #expect(finder.thumbnailURL(for: article, mode: .small) == "https://example.com/thumbnail.jpg") - #expect(imageDatabase.fetchArticleThumbnailsSync(articleIDs: ["1"]).isEmpty) imageDatabase.recordFailure(url: "https://example.com/thumbnail.jpg", statusCode: 404) finder.thumbnailURLDidFail("https://example.com/thumbnail.jpg") @@ -122,21 +116,6 @@ private typealias ArticleAttachment = Articles.Attachment #expect(finder.thumbnailURL(for: differentImages, mode: .small) == "https://example.com/new-image.jpg") } - @Test func savedAndNewThumbnailURLsAreFoundBeforeReturning() async { - let imageDatabase = ImageDatabase(databasePath: ":memory:") - let savedArticle = makeArticle(articleID: "1", contentHTML: #"

"#) - await ArticleThumbnailFinder(imageDatabase: imageDatabase).findThumbnailURLs(for: [savedArticle]).value - - let finderAfterRelaunch = ArticleThumbnailFinder(imageDatabase: imageDatabase) - let newArticle = makeArticle(articleID: "2", contentHTML: #"

"#) - let parsing = finderAfterRelaunch.findThumbnailURLs(for: [savedArticle, newArticle]) - #expect(finderAfterRelaunch.thumbnailURL(for: savedArticle, mode: .large) == "https://example.com/uploads/saved.jpg") - #expect(finderAfterRelaunch.thumbnailURL(for: newArticle, mode: .large) == "https://example.com/uploads/new.jpg") - - await parsing.value - #expect(imageDatabase.fetchArticleThumbnailsSync(articleIDs: ["2"]).first?.thumbnailURLs == ["https://example.com/uploads/new.jpg"]) - } - @Test func articlesPastTheLimitAreParsedAfterReturningAndPostedInBatches() async throws { let finder = ArticleThumbnailFinder(imageDatabase: ImageDatabase(databasePath: ":memory:")) let limit = ArticleThumbnailFinder.maximumArticlesParsedBeforeReturning diff --git a/Modules/Images/Tests/ImagesTests/ImageDatabaseTests.swift b/Modules/Images/Tests/ImagesTests/ImageDatabaseTests.swift index b9bc76a67..3783d4ff7 100644 --- a/Modules/Images/Tests/ImagesTests/ImageDatabaseTests.swift +++ b/Modules/Images/Tests/ImagesTests/ImageDatabaseTests.swift @@ -35,6 +35,31 @@ import RSWeb await imageDatabase.vacuum() } + @Test func articleThumbnailTableIsDropped() 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 tableName = "articleThumbnailURLs" + + let databaseWithTable = FMDatabase.openAndSetUpDatabase(path: databasePath) + databaseWithTable.executeStatements("CREATE TABLE \(tableName) (articleID TEXT PRIMARY KEY NOT NULL, thumbnailURLs TEXT, lastChecked REAL NOT NULL);") + #expect(databaseWithTable.tableExists(tableName)) + databaseWithTable.close() + + let imageDatabase = ImageDatabase(databasePath: databasePath) + // Waits for the cleanup init queues. + await imageDatabase.vacuum() + + let reopenedDatabase = FMDatabase.openAndSetUpDatabase(path: databasePath) + defer { + reopenedDatabase.close() + } + #expect(!reopenedDatabase.tableExists(tableName)) + } + @Test func failedUsageQueryReturnsNil() { let database = FMDatabase.openAndSetUpDatabase(path: ":memory:") defer { diff --git a/iOS/MainTimeline/MainTimelineViewController.swift b/iOS/MainTimeline/MainTimelineViewController.swift index ed28fffee..eed562846 100644 --- a/iOS/MainTimeline/MainTimelineViewController.swift +++ b/iOS/MainTimeline/MainTimelineViewController.swift @@ -1109,7 +1109,7 @@ private extension MainTimelineViewController { } /// Finds thumbnails in the HTML of articles with no provided image. Local work, no downloads. - /// Results for saved articles and the first articles are ready when this returns, so rows laid out next get their final heights. + /// Results for the first articles are ready when this returns, so rows laid out next get their final heights. func findThumbnailURLs() { guard thumbnailMode != nil, let articles, !articles.isEmpty else { return