mirror of
https://github.com/Ranchero-Software/NetNewsWire
synced 2026-12-01 09:50:16 +00:00
Keep a max (currently 60) number of downloads waiting so we’re not downloading for scrolled-past rows too much.
This commit is contained in:
1 parent
beea83ce1b
commit
3db7db4f4a
3 files changed
+53
-17
No files matched your search
@@ -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<Void, Never>]()
|
||||
private var waiting = [CheckedContinuation<Bool, Never>]()
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
@@ -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<Result<Data, ImageDownloadError>, 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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user