From 4f6ff7d5050f268993c4bf65622b14d443bc79e3 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Sun, 1 Nov 2026 11:34:12 -0800 Subject: [PATCH] Make ThumbnailTaskQueue newest-first. Remove priorities, which are no needed. --- .../Images/ArticleThumbnailFinder.swift | 25 ++++----- .../Sources/Images/DownloadedImageCache.swift | 47 +++++----------- .../Sources/Images/ImageDownloader.swift | 2 +- .../Images/SingleFaviconDownloader.swift | 2 +- .../Sources/Images/ThumbnailTaskQueue.swift | 37 ++++-------- .../ImagesTests/ThumbnailTaskQueueTests.swift | 56 +++++++++---------- .../RSWeb/Sources/RSWeb/NetworkMonitor.swift | 7 --- 7 files changed, 64 insertions(+), 112 deletions(-) diff --git a/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift b/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift index 92c23fd57..efd94a769 100644 --- a/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift +++ b/Modules/Images/Sources/Images/ArticleThumbnailFinder.swift @@ -65,7 +65,7 @@ extension Notification.Name { private var articleIDsBeingDiscovered = Set() private let imageCache = NSCache() // See cacheKey private let decodeQueue = ThumbnailTaskQueue(maximumRunningCount: maximumConcurrentDecodes, maximumWaitingCount: maximumWaitingDecodes) - private var prioritiesInProgress = [String: ThumbnailPriority]() // cacheKey: priority, which a prefetch’s row becoming visible changes + private var decodeKeysInProgress = Set() private var urlsThatFailedToDecode = Set() // So a failure notification can’t lead to the same attempt again private var chosenThumbnailURLs = [Mode: [String: ChosenThumbnailURL]]() // articleID: the URL thumbnailURL(for:mode:) chose, since large-mode row heights ask for every row @@ -119,7 +119,7 @@ extension Notification.Name { DownloadedImageCache.shared.imageWasUsed(url, checksForUpdates: false) return image } - findImage(url, mode: mode, priority: .visible, activityDetail: articleTitle) + findImage(url, mode: mode, activityDetail: articleTitle) return nil } @@ -127,7 +127,7 @@ extension Notification.Name { /// Shares the timeline’s copy and any download in progress, so the image is downloaded once. /// A download starts right away rather than waiting behind timeline downloads. public func fullSizeImageData(url: String, articleTitle: String?) async throws(ImageDownloadError) -> Data { - try await DownloadedImageCache.shared.imageData(for: url, downloadPriority: nil, checksForUpdates: false, activityOwner: .thumbnailDownloader, activityKind: .downloadThumbnail(imageURL: url), activityDetail: articleTitle) + try await DownloadedImageCache.shared.imageData(for: url, usesDownloadQueue: false, checksForUpdates: false, activityOwner: .thumbnailDownloader, activityKind: .downloadThumbnail(imageURL: url), activityDetail: articleTitle) } /// Nil when the article has no usable image, or when its HTML hasn’t been checked yet. @@ -282,26 +282,23 @@ private extension ArticleThumbnailFinder { } } - func findImage(_ url: String, mode: Mode, priority: ThumbnailPriority, activityDetail: String?) { + func findImage(_ url: String, mode: Mode, activityDetail: String?) { let cacheKey = Self.cacheKey(url, mode) let decodeKey = cacheKey as String - guard prioritiesInProgress[decodeKey] == nil else { - if priority == .visible { - prioritiesInProgress[decodeKey] = .visible - DownloadedImageCache.shared.prioritizeDownload(for: url) - decodeQueue.prioritize(key: decodeKey) - } + guard !decodeKeysInProgress.contains(decodeKey) else { + DownloadedImageCache.shared.prioritizeDownload(for: url) + decodeQueue.prioritize(key: decodeKey) return } - prioritiesInProgress[decodeKey] = priority + decodeKeysInProgress.insert(decodeKey) Task { defer { - prioritiesInProgress[decodeKey] = nil + decodeKeysInProgress.remove(decodeKey) } do throws(ImageDownloadError) { - let data = try await DownloadedImageCache.shared.imageData(for: url, downloadPriority: priority, checksForUpdates: false, activityOwner: .thumbnailDownloader, activityKind: .downloadThumbnail(imageURL: url), activityDetail: activityDetail) - guard await decodeQueue.waitForTurn(key: decodeKey, priority: prioritiesInProgress[decodeKey] ?? priority) != .dropped else { + let data = try await DownloadedImageCache.shared.imageData(for: url, usesDownloadQueue: true, checksForUpdates: false, activityOwner: .thumbnailDownloader, activityKind: .downloadThumbnail(imageURL: url), activityDetail: activityDetail) + guard await decodeQueue.waitForTurn(key: decodeKey) != .dropped else { return } defer { diff --git a/Modules/Images/Sources/Images/DownloadedImageCache.swift b/Modules/Images/Sources/Images/DownloadedImageCache.swift index 17c7a7207..51ff36add 100644 --- a/Modules/Images/Sources/Images/DownloadedImageCache.swift +++ b/Modules/Images/Sources/Images/DownloadedImageCache.swift @@ -114,26 +114,22 @@ extension Notification.Name { NetworkMonitor.shared.isConnected && !NetworkMonitor.shared.isConstrained } - /// The stored copy, read from disk or downloaded. With a `downloadPriority`, a download + /// The stored copy, read from disk or downloaded. With `usesDownloadQueue`, a download /// waits its turn in the download queue, and doesn’t start when offline or in Low Data Mode. - /// A prefetch also doesn’t start on an expensive network or in Low Power Mode. - /// Without a `downloadPriority`, it starts right away, as does a waiting download for the same URL. + /// Without it, a download starts right away, as does a waiting download for the same URL. /// Activity log fires only when the request reaches the network. - func imageData(for url: String, downloadPriority: ThumbnailPriority?, checksForUpdates: Bool, activityOwner: ActivityOwner?, activityKind: ActivityKind?, activityDetail: String?) async throws(ImageDownloadError) -> Data { + func imageData(for url: String, usesDownloadQueue: Bool, checksForUpdates: Bool, activityOwner: ActivityOwner?, activityKind: ActivityKind?, activityDetail: String?) async throws(ImageDownloadError) -> Data { if let task = tasks[url] { - switch downloadPriority { - case .visible: + if usesDownloadQueue { prioritizeDownload(for: url) - case nil: + } else { downloadQueue.startNow(key: url) - case .prefetch: - break } return try await task.value.get() } let task = Task { - await findImage(url, downloadPriority: downloadPriority, checksForUpdates: checksForUpdates, activityOwner: activityOwner, activityKind: activityKind, activityDetail: activityDetail) + await findImage(url, usesDownloadQueue: usesDownloadQueue, checksForUpdates: checksForUpdates, activityOwner: activityOwner, activityKind: activityKind, activityDetail: activityDetail) } tasks[url] = task let result = await task.value @@ -141,7 +137,7 @@ extension Notification.Name { return try result.get() } - /// Moves a waiting download to the front, for an image that just became visible. + /// Moves a waiting download to the front, for an image whose row is shown again. func prioritizeDownload(for url: String) { downloadQueue.prioritize(key: url) } @@ -193,7 +189,7 @@ extension Notification.Name { private extension DownloadedImageCache { - func findImage(_ url: String, downloadPriority: ThumbnailPriority?, checksForUpdates: Bool, activityOwner: ActivityOwner?, activityKind: ActivityKind?, activityDetail: String?) async -> Result { + func findImage(_ url: String, usesDownloadQueue: Bool, checksForUpdates: Bool, activityOwner: ActivityOwner?, activityKind: ActivityKind?, activityDetail: String?) async -> Result { if let data = await Self.readFromDisk(diskCache, key: Self.diskKey(url)) { imageWasUsed(url, checksForUpdates: checksForUpdates) return .success(data) @@ -206,16 +202,16 @@ private extension DownloadedImageCache { return .failure(ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: true)) } let host = Self.host(url) - if let downloadPriority { - guard Self.networkAllowsDownload(priority: downloadPriority) else { + if usesDownloadQueue { + guard Self.networkAllowsDownloads else { return .failure(ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: true)) } - switch await downloadQueue.waitForTurn(key: url, group: host, priority: downloadPriority) { + switch await downloadQueue.waitForTurn(key: url, group: host) { case .dropped: return .failure(ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: true)) - case .start(let currentPriority): + case .start: // The network or a retry wait may have changed while this was queued. - guard !isWaitingToRetry(url), Self.networkAllowsDownload(priority: currentPriority) else { + guard !isWaitingToRetry(url), Self.networkAllowsDownloads else { downloadQueue.taskDidFinish(group: host) return .failure(ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: true)) } @@ -223,28 +219,15 @@ private extension DownloadedImageCache { break } } - let maximumByteCount = downloadPriority == nil ? nil : Self.maximumLimitedDownloadByteCount + let maximumByteCount = usesDownloadQueue ? Self.maximumLimitedDownloadByteCount : nil let result = await downloadImageFromNetwork(url, maximumByteCount: maximumByteCount, activityOwner: activityOwner, activityKind: activityKind, activityDetail: activityDetail) - if downloadPriority != nil { + if usesDownloadQueue { downloadQueue.taskDidFinish(group: host) } noteDownloadResult(result, url: url) return result } - /// Prefetching also waits for a network that isn’t expensive, such as cellular, and for Low Power Mode to be off. - static func networkAllowsDownload(priority: ThumbnailPriority) -> Bool { - guard networkAllowsDownloads else { - return false - } - switch priority { - case .visible: - return true - case .prefetch: - return !NetworkMonitor.shared.isExpensive && !ProcessInfo.processInfo.isLowPowerModeEnabled - } - } - func isWaitingToRetry(_ url: String) -> Bool { let now = Date() if let retryDate = retryDelays[url]?.retryDate, retryDate > now { diff --git a/Modules/Images/Sources/Images/ImageDownloader.swift b/Modules/Images/Sources/Images/ImageDownloader.swift index ed19600f5..ba7b904a3 100644 --- a/Modules/Images/Sources/Images/ImageDownloader.swift +++ b/Modules/Images/Sources/Images/ImageDownloader.swift @@ -136,7 +136,7 @@ private extension ImageDownloader { } do { - let storedData = try await DownloadedImageCache.shared.imageData(for: url, downloadPriority: nil, checksForUpdates: true, activityOwner: activityOwner, activityKind: activityKind, activityDetail: activityDetail) + let storedData = try await DownloadedImageCache.shared.imageData(for: url, usesDownloadQueue: false, checksForUpdates: true, activityOwner: activityOwner, activityKind: activityKind, activityDetail: activityDetail) let data = await Self.scaledImageData(storedData, maxPixelSize: RSImage.maxIconPixelSize) // An image that’s already small enough needs no second file. if data != storedData { diff --git a/Modules/Images/Sources/Images/SingleFaviconDownloader.swift b/Modules/Images/Sources/Images/SingleFaviconDownloader.swift index a0aa719fd..56ff5a6bb 100644 --- a/Modules/Images/Sources/Images/SingleFaviconDownloader.swift +++ b/Modules/Images/Sources/Images/SingleFaviconDownloader.swift @@ -70,7 +70,7 @@ private extension SingleFaviconDownloader { return } do throws(ImageDownloadError) { - let storedData = try await DownloadedImageCache.shared.imageData(for: faviconURL, downloadPriority: nil, checksForUpdates: true, activityOwner: .faviconDownloader, activityKind: kind, activityDetail: homePageURL) + let storedData = try await DownloadedImageCache.shared.imageData(for: faviconURL, usesDownloadQueue: false, checksForUpdates: true, activityOwner: .faviconDownloader, activityKind: kind, activityDetail: homePageURL) let scaledData = await Self.scaledImageData(storedData, maxPixelSize: RSImage.maxIconPixelSize) // DownloadedImageCache records download failures, but can’t know whether the data decodes as an icon. if let image = await Self.image(scaledData) { diff --git a/Modules/Images/Sources/Images/ThumbnailTaskQueue.swift b/Modules/Images/Sources/Images/ThumbnailTaskQueue.swift index 6f32adf73..cd9a7e960 100644 --- a/Modules/Images/Sources/Images/ThumbnailTaskQueue.swift +++ b/Modules/Images/Sources/Images/ThumbnailTaskQueue.swift @@ -7,33 +7,26 @@ import Foundation -public enum ThumbnailPriority: Sendable { - case visible // Shown now - case prefetch // Expected to be shown soon -} - enum ThumbnailTurn: Equatable, Sendable { case dropped - case start(priority: ThumbnailPriority) // The priority now, which a wait can raise from prefetch to visible - case startNow // Started by `startNow`, whatever its priority + case start + case startNow // Started by `startNow` } /// Decides when thumbnail tasks, such as downloads, may start, and limits how many run at once. /// /// Tasks start most-recent-first, so images for rows the user just scrolled to go ahead -/// of rows already scrolled past. Prefetch tasks start only when no visible task -/// that has room in its group is waiting. A waiting task whose row becomes visible moves to the front. +/// of rows already scrolled past. A waiting task whose row is shown again moves to the front. /// /// Tasks can have a group, such as a download’s host, so that a slow group can’t take every slot. /// -/// When too many are waiting, prefetches are dropped first, then the oldest visible tasks, -/// since their rows are likely long gone. A dropped row that comes back asks again. +/// When too many are waiting, the oldest are dropped, since their rows are likely long gone. +/// A dropped row that comes back asks again. @MainActor final class ThumbnailTaskQueue { private struct WaitingTask { let key: String let group: String? - let priority: ThumbnailPriority let continuation: CheckedContinuation } @@ -42,7 +35,7 @@ enum ThumbnailTurn: Equatable, Sendable { private let maximumRunningCountPerGroup: Int private var runningCount = 0 private var runningCountPerGroup = [String: Int]() - private var waiting = [WaitingTask]() // Prefetches, then visible. Next to start is last. + private var waiting = [WaitingTask]() // Next to start is last var waitingCount: Int { waiting.count @@ -55,20 +48,13 @@ enum ThumbnailTurn: Equatable, Sendable { } /// Call `taskDidFinish` with the same group after the task finishes, unless it was dropped. - func waitForTurn(key: String, group: String? = nil, priority: ThumbnailPriority) async -> ThumbnailTurn { + func waitForTurn(key: String, group: String? = nil) async -> ThumbnailTurn { if runningCount < maximumRunningCount, hasRoom(in: group) { noteTaskStarted(group: group) - return .start(priority: priority) + return .start } return await withCheckedContinuation { continuation in - let waitingTask = WaitingTask(key: key, group: group, priority: priority, continuation: continuation) - switch priority { - case .visible: - waiting.append(waitingTask) - case .prefetch: - let firstVisibleIndex = waiting.firstIndex { $0.priority == .visible } ?? waiting.endIndex - waiting.insert(waitingTask, at: firstVisibleIndex) - } + waiting.append(WaitingTask(key: key, group: group, continuation: continuation)) if waiting.count > maximumWaitingCount { waiting.removeFirst().continuation.resume(returning: .dropped) } @@ -89,7 +75,7 @@ enum ThumbnailTurn: Equatable, Sendable { } let next = waiting.remove(at: index) noteTaskStarted(group: next.group) - next.continuation.resume(returning: .start(priority: next.priority)) + next.continuation.resume(returning: .start) } /// Moves a waiting task to the front. @@ -97,8 +83,7 @@ enum ThumbnailTurn: Equatable, Sendable { guard let index = waiting.lastIndex(where: { $0.key == key }) else { return } - let waitingTask = waiting.remove(at: index) - waiting.append(WaitingTask(key: key, group: waitingTask.group, priority: .visible, continuation: waitingTask.continuation)) + waiting.append(waiting.remove(at: index)) } /// Starts a waiting task now, even when that goes over the limit. diff --git a/Modules/Images/Tests/ImagesTests/ThumbnailTaskQueueTests.swift b/Modules/Images/Tests/ImagesTests/ThumbnailTaskQueueTests.swift index 48ef03afe..2b1c4c79b 100644 --- a/Modules/Images/Tests/ImagesTests/ThumbnailTaskQueueTests.swift +++ b/Modules/Images/Tests/ImagesTests/ThumbnailTaskQueueTests.swift @@ -13,46 +13,40 @@ import Testing @Test func oldestWaitingDownloadIsDroppedAndNewestGoesFirst() async { let queue = ThumbnailTaskQueue(maximumRunningCount: 1, maximumWaitingCount: 2) - #expect(await queue.waitForTurn(key: "running", priority: .visible) == .start(priority: .visible)) + #expect(await queue.waitForTurn(key: "running") == .start) - let oldest = await startWaitingTask(queue: queue, key: "oldest", priority: .visible) - let middle = await startWaitingTask(queue: queue, key: "middle", priority: .visible) - let newest = Task { await queue.waitForTurn(key: "newest", priority: .visible) } + let oldest = await startWaitingTask(queue: queue, key: "oldest") + let middle = await startWaitingTask(queue: queue, key: "middle") + let newest = Task { await queue.waitForTurn(key: "newest") } // Waiting for the drop also means the newest task is in the queue. #expect(await oldest.value == .dropped) queue.taskDidFinish() - #expect(await newest.value == .start(priority: .visible)) + #expect(await newest.value == .start) queue.taskDidFinish() - #expect(await middle.value == .start(priority: .visible)) + #expect(await middle.value == .start) } - @Test func prefetchWaitsBehindVisibleUntilItBecomesVisible() async { + @Test func prioritizedTaskGoesAheadOfNewerTask() async { let queue = ThumbnailTaskQueue(maximumRunningCount: 1, maximumWaitingCount: 10) - #expect(await queue.waitForTurn(key: "running", priority: .visible) == .start(priority: .visible)) + #expect(await queue.waitForTurn(key: "running") == .start) - let firstPrefetch = await startWaitingTask(queue: queue, key: "firstPrefetch", priority: .prefetch) - let visible = await startWaitingTask(queue: queue, key: "visible", priority: .visible) - let secondPrefetch = await startWaitingTask(queue: queue, key: "secondPrefetch", priority: .prefetch) + let older = await startWaitingTask(queue: queue, key: "older") + let newer = await startWaitingTask(queue: queue, key: "newer") - // Visible goes first, even though the second prefetch was requested later. + queue.prioritize(key: "older") queue.taskDidFinish() - #expect(await visible.value == .start(priority: .visible)) - - // The first prefetch became visible, so it goes ahead of the newer second prefetch. - queue.prioritize(key: "firstPrefetch") + #expect(await older.value == .start) queue.taskDidFinish() - #expect(await firstPrefetch.value == .start(priority: .visible)) - queue.taskDidFinish() - #expect(await secondPrefetch.value == .start(priority: .prefetch)) + #expect(await newer.value == .start) } @Test func articleViewImageStartsWithoutWaitingForASlot() async { let queue = ThumbnailTaskQueue(maximumRunningCount: 1, maximumWaitingCount: 10) - #expect(await queue.waitForTurn(key: "running", priority: .visible) == .start(priority: .visible)) + #expect(await queue.waitForTurn(key: "running") == .start) - let articleImage = await startWaitingTask(queue: queue, key: "articleImage", priority: .prefetch) + let articleImage = await startWaitingTask(queue: queue, key: "articleImage") // Starts while the running download still holds the only slot. queue.startNow(key: "articleImage") @@ -63,33 +57,33 @@ import Testing let slowHost = "slow.example.com" let fastHost = "fast.example.com" let queue = ThumbnailTaskQueue(maximumRunningCount: 2, maximumWaitingCount: 10, maximumRunningCountPerGroup: 1) - #expect(await queue.waitForTurn(key: "slow1", group: slowHost, priority: .visible) == .start(priority: .visible)) - let slow2 = await startWaitingTask(queue: queue, key: "slow2", group: slowHost, priority: .visible) + #expect(await queue.waitForTurn(key: "slow1", group: slowHost) == .start) + let slow2 = await startWaitingTask(queue: queue, key: "slow2", group: slowHost) // Starts even though slow2 is waiting, since slow2’s host is at its limit. - #expect(await queue.waitForTurn(key: "fast1", group: fastHost, priority: .visible) == .start(priority: .visible)) + #expect(await queue.waitForTurn(key: "fast1", group: fastHost) == .start) - let fast2 = await startWaitingTask(queue: queue, key: "fast2", group: fastHost, priority: .visible) - let slow3 = await startWaitingTask(queue: queue, key: "slow3", group: slowHost, priority: .visible) + let fast2 = await startWaitingTask(queue: queue, key: "fast2", group: fastHost) + let slow3 = await startWaitingTask(queue: queue, key: "slow3", group: slowHost) // slow3 is the newest, but its host is still at its limit. queue.taskDidFinish(group: fastHost) - #expect(await fast2.value == .start(priority: .visible)) + #expect(await fast2.value == .start) queue.taskDidFinish(group: slowHost) - #expect(await slow3.value == .start(priority: .visible)) + #expect(await slow3.value == .start) queue.taskDidFinish(group: slowHost) - #expect(await slow2.value == .start(priority: .visible)) + #expect(await slow2.value == .start) } } private extension ThumbnailTaskQueueTests { /// Returns once the task is in the queue, so the order tasks are queued in doesn’t depend on scheduling. - func startWaitingTask(queue: ThumbnailTaskQueue, key: String, group: String? = nil, priority: ThumbnailPriority) async -> Task { + func startWaitingTask(queue: ThumbnailTaskQueue, key: String, group: String? = nil) async -> Task { let waitingCount = queue.waitingCount - let task = Task { await queue.waitForTurn(key: key, group: group, priority: priority) } + let task = Task { await queue.waitForTurn(key: key, group: group) } while queue.waitingCount == waitingCount { await Task.yield() } diff --git a/Modules/RSWeb/Sources/RSWeb/NetworkMonitor.swift b/Modules/RSWeb/Sources/RSWeb/NetworkMonitor.swift index 51cdff396..b64628ba8 100644 --- a/Modules/RSWeb/Sources/RSWeb/NetworkMonitor.swift +++ b/Modules/RSWeb/Sources/RSWeb/NetworkMonitor.swift @@ -23,7 +23,6 @@ nonisolated public final class NetworkMonitor: Sendable { private struct State: Sendable { var isConnected: Bool? var connectionType: NWInterface.InterfaceType? - var isExpensive = false var isConstrained = false } @@ -39,11 +38,6 @@ nonisolated public final class NetworkMonitor: Sendable { state.withLock { $0.connectionType } } - /// Is the connection expensive (cellular data with limited plan, for instance) - public var isExpensive: Bool { - state.withLock { $0.isExpensive } - } - /// Is the connection constrained (Low Data Mode enabled, for instance) public var isConstrained: Bool { state.withLock { $0.isConstrained } @@ -78,7 +72,6 @@ nonisolated public final class NetworkMonitor: Sendable { let statusDidChange = isConnected != (state.isConnected ?? true) || path.isConstrained != state.isConstrained state.isConnected = isConnected state.connectionType = path.availableInterfaces.first?.type - state.isExpensive = path.isExpensive state.isConstrained = path.isConstrained return statusDidChange }