Make ThumbnailTaskQueue newest-first. Remove priorities, which are no needed.

This commit is contained in:
Brent Simmons committed 2026-11-01 11:34:12 -08:00
1 parent 35ae2068c1
commit 4f6ff7d505
7 files changed
+64 -112

No files matched your search

@@ -65,7 +65,7 @@ extension Notification.Name {
private var articleIDsBeingDiscovered = Set<String>()
private let imageCache = NSCache<NSString, RSImage>() // 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<String>()
private var urlsThatFailedToDecode = Set<String>() // 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 {
@@ -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<Data, ImageDownloadError> {
func findImage(_ url: String, usesDownloadQueue: Bool, checksForUpdates: Bool, activityOwner: ActivityOwner?, activityKind: ActivityKind?, activityDetail: String?) async -> Result<Data, ImageDownloadError> {
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 {
@@ -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 {
@@ -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) {
@@ -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<ThumbnailTurn, Never>
}
@@ -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.
@@ -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<ThumbnailTurn, Never> {
func startWaitingTask(queue: ThumbnailTaskQueue, key: String, group: String? = nil) async -> Task<ThumbnailTurn, Never> {
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()
}
@@ -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
}