diff --git a/Modules/Images/Sources/Images/DownloadLimiter.swift b/Modules/Images/Sources/Images/DownloadLimiter.swift index dfd37103e..6a6c7f215 100644 --- a/Modules/Images/Sources/Images/DownloadLimiter.swift +++ b/Modules/Images/Sources/Images/DownloadLimiter.swift @@ -10,14 +10,18 @@ import RSWeb /// Limits how many downloads run at once. Waiting downloads start most-recent-first, /// so images for rows the user just scrolled to go ahead of rows already scrolled past. +/// When too many are waiting, the oldest are dropped, since their rows are likely long gone. +/// A dropped row that comes back asks again, and goes to the front. @MainActor final class DownloadLimiter { private let maximumConcurrentDownloads: Int + private let maximumWaitingDownloads: Int private var runningCount = 0 - private var waiting = [CheckedContinuation]() + private var waiting = [CheckedContinuation]() - init(maximumConcurrentDownloads: Int) { + init(maximumConcurrentDownloads: Int, maximumWaitingDownloads: Int) { self.maximumConcurrentDownloads = maximumConcurrentDownloads + self.maximumWaitingDownloads = maximumWaitingDownloads } /// False when offline or in Low Data Mode. @@ -25,21 +29,25 @@ import RSWeb NetworkMonitor.shared.isConnected && !NetworkMonitor.shared.isConstrained } - /// Returns when a download may start. Call `downloadDidFinish` after it finishes. - func waitForTurn() async { + /// Returns true when the download may start. Call `downloadDidFinish` after it finishes. + /// Returns false when the download was dropped. Don’t call `downloadDidFinish` then. + func waitForTurn() async -> Bool { if runningCount < maximumConcurrentDownloads { runningCount += 1 - return + return true } - await withCheckedContinuation { continuation in + return await withCheckedContinuation { continuation in waiting.append(continuation) + if waiting.count > maximumWaitingDownloads { + waiting.removeFirst().resume(returning: false) + } } } func downloadDidFinish() { // The finished download’s slot passes straight to the next one. if let next = waiting.popLast() { - next.resume() + next.resume(returning: true) } else { runningCount -= 1 } diff --git a/Modules/Images/Sources/Images/DownloadedImageCache.swift b/Modules/Images/Sources/Images/DownloadedImageCache.swift index 834d31411..34fffcf5c 100644 --- a/Modules/Images/Sources/Images/DownloadedImageCache.swift +++ b/Modules/Images/Sources/Images/DownloadedImageCache.swift @@ -36,6 +36,8 @@ import ActivityLog private static let folderName = "DownloadedImages" nonisolated private static let compressionQuality = 0.8 private static let maximumConcurrentLimitedDownloads = 4 + /// A few screens of thumbnails. + private static let maximumWaitingLimitedDownloads = 60 #if os(macOS) private static let limit = ByteLimit(maximumByteCount: 300 * 1024 * 1024) @@ -60,7 +62,7 @@ import ActivityLog nonisolated private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "DownloadedImageCache") private let diskCache: BinaryDiskCache - private let downloadLimiter = DownloadLimiter(maximumConcurrentDownloads: maximumConcurrentLimitedDownloads) + private let downloadLimiter = DownloadLimiter(maximumConcurrentDownloads: maximumConcurrentLimitedDownloads, maximumWaitingDownloads: maximumWaitingLimitedDownloads) private var tasks = [String: Task, Never>]() // url: task private var totalByteCount: Int? // Nil while a removal pass counts it private var removalByteCount = limit.maximumByteCount // A save that takes the total over this starts a pass @@ -102,10 +104,9 @@ private extension DownloadedImageCache { } if usesDownloadLimiter { - guard downloadLimiter.networkAllowsDownloads else { + guard downloadLimiter.networkAllowsDownloads, await downloadLimiter.waitForTurn() else { return .failure(ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: true)) } - await downloadLimiter.waitForTurn() } let result = await downloadImageFromNetwork(url, activityOwner: activityOwner, activityKind: activityKind, activityDetail: activityDetail) if usesDownloadLimiter { @@ -205,21 +206,16 @@ private extension DownloadedImageCache { // MARK: - Revalidating Images - /// Waits behind other downloads using the download limiter. + /// Doesn’t use the download limiter, since icons aren’t limited either. /// A network error leaves `nextCheck` as is, so the next day’s use tries again. func revalidateIfDue(_ url: String) async { guard let validation = await ImageMetadataDatabase.shared.fetchDownloadedImageValidation(url: url), validation.nextCheck <= Date() else { return } - guard let imageURL = URL(string: url), downloadLimiter.networkAllowsDownloads else { + guard let imageURL = URL(string: url) else { return } - await downloadLimiter.waitForTurn() - defer { - downloadLimiter.downloadDidFinish() - } - var urlRequest = URLRequest(url: imageURL) validation.conditionalGetInfo?.addRequestHeadersToURLRequest(&urlRequest) let downloadResponse: DownloadResponse diff --git a/Modules/Images/Tests/ImagesTests/DownloadLimiterTests.swift b/Modules/Images/Tests/ImagesTests/DownloadLimiterTests.swift new file mode 100644 index 000000000..9d8d8d028 --- /dev/null +++ b/Modules/Images/Tests/ImagesTests/DownloadLimiterTests.swift @@ -0,0 +1,32 @@ +// +// DownloadLimiterTests.swift +// ImagesTests +// +// Created by Brent Simmons on 10/27/26. +// + +import Foundation +import Testing +@testable import Images + +@MainActor @Suite struct DownloadLimiterTests { + + @Test func oldestWaitingDownloadIsDroppedAndNewestGoesFirst() async { + let limiter = DownloadLimiter(maximumConcurrentDownloads: 1, maximumWaitingDownloads: 2) + #expect(await limiter.waitForTurn()) + + let oldest = Task { await limiter.waitForTurn() } + await Task.yield() + let middle = Task { await limiter.waitForTurn() } + await Task.yield() + let newest = Task { await limiter.waitForTurn() } + await Task.yield() + + #expect(await oldest.value == false) + + limiter.downloadDidFinish() + #expect(await newest.value) + limiter.downloadDidFinish() + #expect(await middle.value) + } +}