From 24ab32aa80c619d9039f4782df120bf2c5afc76a Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Sun, 1 Nov 2026 20:45:26 -0800 Subject: [PATCH] Parse HTML thumbnails for first 1,000 articles before rows load, so we have thumbnail state for layout. --- .../Images/ArticleThumbnailFinder.swift | 55 +++++++++++++------ .../ArticleThumbnailFinderTests.swift | 22 +++++--- .../MainTimelineViewController.swift | 2 +- 3 files changed, 53 insertions(+), 26 deletions(-) diff --git a/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift b/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift index efd94a769..34fe4ecfb 100644 --- a/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift +++ b/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift @@ -39,9 +39,8 @@ extension Notification.Name { /// tries them in that order. Large mode tries the article’s image and attachments /// 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 off the main thread -/// by `findThumbnailURLs(for:)`, and the results are saved in `ImageDatabase`, -/// so each article’s HTML is parsed once. +/// 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. /// /// 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. @@ -89,6 +88,8 @@ extension Notification.Name { nonisolated private static let maxHTMLThumbnailURLsPerArticle = 3 /// Articles parsed and saved at a time, which also limits how long a save holds the database queue. 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. private static let maxCachedArticleCount = 50_000 /// Entries per mode in chosenThumbnailURLs. Past this, that mode’s entries are emptied. @@ -146,10 +147,10 @@ extension Notification.Name { } /// Looks for thumbnails in the HTML of articles that have no usable provided image. - /// Results saved in the database are ready when this returns, so that rows laid out next can use them. - /// This blocks until the database has answered. - /// The rest are parsed off the main thread and saved in batches, in the order given, so the first rows don’t wait for the last. - /// `.articleThumbnailURLsDidBecomeAvailable` is posted after each batch for those that have thumbnails. + /// 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 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. @discardableResult public func findThumbnailURLs(for articles: some Collection
) -> Task { if htmlThumbnailURLs.count > Self.maxCachedArticleCount { @@ -162,23 +163,30 @@ extension Notification.Name { } let articleHTMLs = articlesToFind.filter { !isCached($0.articleID) }.compactMap(ArticleHTML.init) - let articleIDs = articleHTMLs.map(\.articleID) - articleIDsBeingDiscovered.formUnion(articleIDs) + let recordsParsedBeforeReturning = Self.thumbnailRecords(Array(articleHTMLs.prefix(Self.maximumArticlesParsedBeforeReturning))) + cacheRecords(recordsParsedBeforeReturning) + + let articleHTMLsToParseLater = Array(articleHTMLs.dropFirst(Self.maximumArticlesParsedBeforeReturning)) + let articleIDsToParseLater = articleHTMLsToParseLater.map(\.articleID) + articleIDsBeingDiscovered.formUnion(articleIDsToParseLater) return Task { defer { - articleIDsBeingDiscovered.subtract(articleIDs) + articleIDsBeingDiscovered.subtract(articleIDsToParseLater) } - for batchStart in stride(from: 0, to: articleHTMLs.count, by: Self.parsingBatchSize) { - let batchEnd = min(batchStart + Self.parsingBatchSize, articleHTMLs.count) - let parsedRecords = await Self.parseThumbnailURLs(Array(articleHTMLs[batchStart.. [ArticleThumbnailRecord] { + thumbnailRecords(articleHTMLs) + } + + nonisolated static func thumbnailRecords(_ articleHTMLs: [ArticleHTML]) -> [ArticleThumbnailRecord] { articleHTMLs.map { articleHTML in let thumbnailURLs = HTMLImageParser.significantImageURLStrings(html: articleHTML.html, baseURL: articleHTML.baseURL, maximumCount: maxHTMLThumbnailURLsPerArticle) return ArticleThumbnailRecord(articleID: articleHTML.articleID, thumbnailURLs: thumbnailURLs) diff --git a/Modules/Images/Tests/ImagesTests/ArticleThumbnailFinderTests.swift b/Modules/Images/Tests/ImagesTests/ArticleThumbnailFinderTests.swift index d726c220f..62c5fce25 100644 --- a/Modules/Images/Tests/ImagesTests/ArticleThumbnailFinderTests.swift +++ b/Modules/Images/Tests/ImagesTests/ArticleThumbnailFinderTests.swift @@ -122,7 +122,7 @@ private typealias ArticleAttachment = Articles.Attachment #expect(finder.thumbnailURL(for: differentImages, mode: .small) == "https://example.com/new-image.jpg") } - @Test func savedThumbnailURLsAreFoundBeforeReturningAndTheRestAreParsed() async { + @Test func savedAndNewThumbnailURLsAreFoundBeforeReturning() async { let imageDatabase = ImageDatabase(databasePath: ":memory:") let savedArticle = makeArticle(articleID: "1", contentHTML: #"

"#) await ArticleThumbnailFinder(imageDatabase: imageDatabase).findThumbnailURLs(for: [savedArticle]).value @@ -131,20 +131,28 @@ private typealias ArticleAttachment = Articles.Attachment 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) == nil) + #expect(finderAfterRelaunch.thumbnailURL(for: newArticle, mode: .large) == "https://example.com/uploads/new.jpg") await parsing.value - #expect(finderAfterRelaunch.thumbnailURL(for: newArticle, mode: .large) == "https://example.com/uploads/new.jpg") + #expect(imageDatabase.fetchArticleThumbnailsSync(articleIDs: ["2"]).first?.thumbnailURLs == ["https://example.com/uploads/new.jpg"]) } - @Test func parsedThumbnailURLsArePostedInBatches() async { + @Test func articlesPastTheLimitAreParsedAfterReturningAndPostedInBatches() async throws { let finder = ArticleThumbnailFinder(imageDatabase: ImageDatabase(databasePath: ":memory:")) - let articles = (0...ArticleThumbnailFinder.parsingBatchSize).map { makeArticle(articleID: String($0), contentHTML: #"

"#) } + let limit = ArticleThumbnailFinder.maximumArticlesParsedBeforeReturning + let batchSize = ArticleThumbnailFinder.parsingBatchSize + let articles = (0...(limit + batchSize)).map { makeArticle(articleID: String($0), contentHTML: #"

"#) } + let lastArticleParsedBeforeReturning = articles[limit - 1] + let lastArticle = try #require(articles.last) let recorder = ThumbnailURLNotificationRecorder(finder: finder) - await finder.findThumbnailURLs(for: articles).value + let parsing = finder.findThumbnailURLs(for: articles) + #expect(finder.thumbnailURL(for: lastArticleParsedBeforeReturning, mode: .small) == "https://example.com/uploads/photo.jpg") + #expect(finder.thumbnailURL(for: lastArticle, mode: .small) == nil) - #expect(recorder.articleIDCounts == [ArticleThumbnailFinder.parsingBatchSize, 1]) + await parsing.value + #expect(finder.thumbnailURL(for: lastArticle, mode: .small) == "https://example.com/uploads/photo.jpg") + #expect(recorder.articleIDCounts == [limit, batchSize, 1]) } @Test func thumbnailTooSmallIsRejected() async throws { diff --git a/iOS/MainTimeline/MainTimelineViewController.swift b/iOS/MainTimeline/MainTimelineViewController.swift index fcf9fc571..ed28fffee 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. - /// Saved results are ready when this returns, so rows laid out next get their final heights. + /// Results for saved articles and 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