mirror of
https://github.com/Ranchero-Software/NetNewsWire
synced 2026-12-05 03:37:41 +00:00
Delete least recently used images on disk once a size cap is reached.
This commit is contained in:
1 parent
fd191c154f
commit
ebfa6ed0e4
5 files changed
+280
-5
No files matched your search
@@ -17,6 +17,10 @@ import ActivityLog
|
||||
/// or kept as is when it’s already smaller. `ImageDownloader` and `ArticleThumbnailFinder`
|
||||
/// make their own sizes from it.
|
||||
/// Requests for a URL that’s already being read or downloaded share that work.
|
||||
///
|
||||
/// Copies on disk are kept until they total more than `limit`. Then the least recently used are
|
||||
/// deleted from disk, except those used in the last few days, which may still be on screen.
|
||||
/// `hardLimit` caps those too. That’s checked at launch and whenever a download goes over the limit.
|
||||
@MainActor final class DownloadedImageCache {
|
||||
|
||||
static let shared = DownloadedImageCache()
|
||||
@@ -28,15 +32,37 @@ import ActivityLog
|
||||
nonisolated private static let compressionQuality = 0.8
|
||||
private static let maximumConcurrentLimitedDownloads = 4
|
||||
|
||||
#if os(macOS)
|
||||
private static let limit = ByteLimit(maximumByteCount: 300 * 1024 * 1024)
|
||||
private static let hardLimit = ByteLimit(maximumByteCount: 1024 * 1024 * 1024)
|
||||
#else
|
||||
private static let limit = ByteLimit(maximumByteCount: 150 * 1024 * 1024)
|
||||
private static let hardLimit = ByteLimit(maximumByteCount: 500 * 1024 * 1024)
|
||||
#endif
|
||||
/// When recently used images keep the total over `limit`, the next pass waits for this much more.
|
||||
private static let byteCountBetweenPasses = limit.maximumByteCount / 10
|
||||
private static let accessDateSaveInterval = TimeInterval(days: 1)
|
||||
/// Images used this recently are removed only to stay under `hardLimit`.
|
||||
nonisolated private static let recentUseInterval = TimeInterval(days: 3)
|
||||
/// A file and its record are saved moments apart, so anything this recent may be mid-save.
|
||||
nonisolated private static let recentChangeInterval: TimeInterval = 60
|
||||
|
||||
nonisolated private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "DownloadedImageCache")
|
||||
|
||||
private let diskCache: BinaryDiskCache
|
||||
private let downloadLimiter = DownloadLimiter(maximumConcurrentDownloads: maximumConcurrentLimitedDownloads)
|
||||
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
|
||||
private var accessDatesSaved = [String: Date]() // url: date
|
||||
|
||||
private init() {
|
||||
let folder = AppConfig.cacheSubfolder(named: Self.folderName)
|
||||
self.diskCache = BinaryDiskCache(folder: folder.path)
|
||||
|
||||
Task {
|
||||
await self.removeImagesOverSizeLimit()
|
||||
}
|
||||
}
|
||||
|
||||
/// The stored copy, read from disk or downloaded. Downloads that use the download limiter
|
||||
@@ -61,6 +87,7 @@ private extension DownloadedImageCache {
|
||||
|
||||
func findImage(_ url: String, usesDownloadLimiter: Bool, activityOwner: ActivityOwner?, activityKind: ActivityKind?, activityDetail: String?) async -> Result<Data, ImageDownloadError> {
|
||||
if let data = await Self.readFromDisk(diskCache, key: Self.diskKey(url)) {
|
||||
saveAccessDateIfNeeded(url)
|
||||
return .success(data)
|
||||
}
|
||||
|
||||
@@ -121,12 +148,14 @@ private extension DownloadedImageCache {
|
||||
let statusCode = httpResponse?.statusCode
|
||||
if let data = downloadResponse.data, !data.isEmpty, let response = downloadResponse.response, response.statusIsOK {
|
||||
let storedImage = await Self.storedImage(data)
|
||||
await Self.saveToDisk(diskCache, key: Self.diskKey(url), data: storedImage.data)
|
||||
let key = Self.diskKey(url)
|
||||
await Self.saveToDisk(diskCache, key: key, data: storedImage.data)
|
||||
var conditionalGetInfo: HTTPConditionalGetInfo?
|
||||
if let httpResponse {
|
||||
conditionalGetInfo = HTTPConditionalGetInfo(urlResponse: httpResponse)
|
||||
}
|
||||
ImageMetadataDatabase.shared.saveDownloadedImage(DownloadedImageRecord(url: url, byteCount: storedImage.data.count, pixelSize: storedImage.pixelSize, conditionalGetInfo: conditionalGetInfo))
|
||||
imageWasSaved(byteCount: storedImage.data.count)
|
||||
return (storedImage.data, downloadResponse)
|
||||
}
|
||||
|
||||
@@ -141,8 +170,50 @@ private extension DownloadedImageCache {
|
||||
throw ImageDownloadError(statusCode: statusCode, decodingFailed: false, isTransient: isTransient)
|
||||
}
|
||||
|
||||
static func diskKey(_ url: String) -> String {
|
||||
url.md5String
|
||||
// MARK: - Removing Images
|
||||
|
||||
/// Saved at most once a day per image, since it only orders images for removal.
|
||||
func saveAccessDateIfNeeded(_ url: String) {
|
||||
let now = Date()
|
||||
if let accessDate = accessDatesSaved[url], now.timeIntervalSince(accessDate) < Self.accessDateSaveInterval {
|
||||
return
|
||||
}
|
||||
accessDatesSaved[url] = now
|
||||
ImageMetadataDatabase.shared.saveDownloadedImageAccessDate(url: url)
|
||||
}
|
||||
|
||||
func imageWasSaved(byteCount: Int) {
|
||||
guard let totalByteCount else {
|
||||
return
|
||||
}
|
||||
let updatedTotalByteCount = totalByteCount + byteCount
|
||||
self.totalByteCount = updatedTotalByteCount
|
||||
if updatedTotalByteCount > removalByteCount {
|
||||
Task {
|
||||
await removeImagesOverSizeLimit()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the least recently used images until the total is `byteCountAfterRemoval`.
|
||||
/// Also removes files with no record and records with no file, so the total matches the disk.
|
||||
/// Saves don’t start another pass while `totalByteCount` is nil.
|
||||
func removeImagesOverSizeLimit() async {
|
||||
totalByteCount = nil
|
||||
let startDate = Date()
|
||||
|
||||
let records = await ImageMetadataDatabase.shared.fetchDownloadedImageUsageByLeastRecentAccess()
|
||||
let fileDates = await Self.fileModificationDates(diskCache)
|
||||
let removal = Self.imageRemoval(records: records, fileDates: fileDates, now: startDate, limit: Self.limit, hardLimit: Self.hardLimit)
|
||||
|
||||
totalByteCount = removal.remainingByteCount
|
||||
removalByteCount = max(Self.limit.maximumByteCount, removal.remainingByteCount + Self.byteCountBetweenPasses)
|
||||
guard !removal.urls.isEmpty || !removal.keys.isEmpty else {
|
||||
return
|
||||
}
|
||||
ImageMetadataDatabase.shared.deleteDownloadedImages(urls: removal.urls)
|
||||
await Self.deleteFromDisk(diskCache, keys: removal.keys)
|
||||
Self.logger.info("Removed \(removal.keys.count) files and \(removal.urls.count) records. \(removal.remainingByteCount) bytes remain.")
|
||||
}
|
||||
|
||||
/// Data that ImageIO can’t read, such as SVG, is kept as is, since `RSImage` may still read it.
|
||||
@@ -161,4 +232,94 @@ private extension DownloadedImageCache {
|
||||
@concurrent static func saveToDisk(_ diskCache: BinaryDiskCache, key: String, data: Data) async {
|
||||
diskCache[key] = data
|
||||
}
|
||||
|
||||
/// Keys are file names.
|
||||
@concurrent static func fileModificationDates(_ diskCache: BinaryDiskCache) async -> [String: Date] {
|
||||
let folderURL = URL(fileURLWithPath: diskCache.folder)
|
||||
guard let fileURLs = try? FileManager.default.contentsOfDirectory(at: folderURL, includingPropertiesForKeys: [.contentModificationDateKey]) else {
|
||||
return [:]
|
||||
}
|
||||
var fileDates = [String: Date]()
|
||||
for fileURL in fileURLs {
|
||||
fileDates[fileURL.lastPathComponent] = (try? fileURL.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate ?? .distantPast
|
||||
}
|
||||
return fileDates
|
||||
}
|
||||
|
||||
@concurrent static func deleteFromDisk(_ diskCache: BinaryDiskCache, keys: Set<String>) async {
|
||||
for key in keys {
|
||||
diskCache[key] = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Disk Keys and Removal
|
||||
|
||||
extension DownloadedImageCache {
|
||||
|
||||
nonisolated static func diskKey(_ url: String) -> String {
|
||||
url.md5String
|
||||
}
|
||||
|
||||
struct ByteLimit {
|
||||
let maximumByteCount: Int
|
||||
/// Removing more than needed means removal doesn’t run again with every download.
|
||||
let byteCountAfterRemoval: Int
|
||||
|
||||
init(maximumByteCount: Int) {
|
||||
self.maximumByteCount = maximumByteCount
|
||||
self.byteCountAfterRemoval = maximumByteCount / 5 * 4
|
||||
}
|
||||
}
|
||||
|
||||
struct ImageRemoval: Equatable {
|
||||
let urls: [String] // Records to delete
|
||||
let keys: Set<String> // Files to delete
|
||||
let remainingByteCount: Int
|
||||
}
|
||||
|
||||
/// `records` are least recently accessed first. Files with no record and records with no file
|
||||
/// are removed. Then, when over `limit`, the least recently accessed images not used recently
|
||||
/// are removed, and when still over `hardLimit`, the least recently accessed of the rest.
|
||||
/// Nothing changed in the last minute is removed, since it may be in the middle of being saved.
|
||||
nonisolated static func imageRemoval(records: [DownloadedImageUsage], fileDates: [String: Date], now: Date, limit: ByteLimit, hardLimit: ByteLimit) -> ImageRemoval {
|
||||
let recentChangeDate = now.addingTimeInterval(-recentChangeInterval)
|
||||
let recentUseDate = now.addingTimeInterval(-recentUseInterval)
|
||||
|
||||
var recordsToKeep = [(record: DownloadedImageUsage, key: String)]()
|
||||
var recordedKeys = Set<String>()
|
||||
var urls = [String]()
|
||||
for record in records {
|
||||
let key = diskKey(record.url)
|
||||
recordedKeys.insert(key)
|
||||
if fileDates[key] == nil && record.lastAccessed < recentChangeDate {
|
||||
urls.append(record.url)
|
||||
} else {
|
||||
recordsToKeep.append((record: record, key: key))
|
||||
}
|
||||
}
|
||||
var keys = Set(fileDates.filter { !recordedKeys.contains($0.key) && $0.value < recentChangeDate }.keys)
|
||||
var byteCount = recordsToKeep.reduce(0) { $0 + $1.record.byteCount }
|
||||
|
||||
func removeLeastRecentlyUsed(accessedBefore date: Date, limit: ByteLimit) {
|
||||
guard byteCount > limit.maximumByteCount else {
|
||||
return
|
||||
}
|
||||
for (record, key) in recordsToKeep {
|
||||
if byteCount <= limit.byteCountAfterRemoval || record.lastAccessed >= date {
|
||||
break
|
||||
}
|
||||
if keys.contains(key) {
|
||||
continue
|
||||
}
|
||||
urls.append(record.url)
|
||||
keys.insert(key)
|
||||
byteCount -= record.byteCount
|
||||
}
|
||||
}
|
||||
removeLeastRecentlyUsed(accessedBefore: recentUseDate, limit: limit)
|
||||
removeLeastRecentlyUsed(accessedBefore: recentChangeDate, limit: hardLimit)
|
||||
|
||||
return ImageRemoval(urls: urls, keys: keys, remainingByteCount: byteCount)
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import RSCore
|
||||
import RSWeb
|
||||
import RSDatabase
|
||||
import RSDatabaseObjC
|
||||
@@ -18,6 +19,13 @@ struct DownloadedImageRecord: Sendable {
|
||||
let conditionalGetInfo: HTTPConditionalGetInfo?
|
||||
}
|
||||
|
||||
/// What `DownloadedImageCache` needs to choose images to remove.
|
||||
struct DownloadedImageUsage: Sendable {
|
||||
let url: String
|
||||
let byteCount: Int
|
||||
let lastAccessed: Date
|
||||
}
|
||||
|
||||
/// One row per copy stored by `DownloadedImageCache`.
|
||||
struct DownloadedImageTable {
|
||||
|
||||
@@ -33,6 +41,9 @@ struct DownloadedImageTable {
|
||||
static let lastModified = "lastModified"
|
||||
}
|
||||
|
||||
/// Keeps each query under the database’s limit on parameters.
|
||||
private static let maximumURLsPerQuery = 500
|
||||
|
||||
/// Every row’s URL and pixel size. `pixelSize` is nil when ImageIO couldn’t read the image.
|
||||
static func fetchPixelSizes(database: FMDatabase) -> [(url: String, pixelSize: (width: Int, height: Int)?)] {
|
||||
var results = [(url: String, pixelSize: (width: Int, height: Int)?)]()
|
||||
@@ -55,6 +66,35 @@ struct DownloadedImageTable {
|
||||
return results
|
||||
}
|
||||
|
||||
/// Least recently accessed first.
|
||||
static func fetchUsageByLeastRecentAccess(database: FMDatabase) -> [DownloadedImageUsage] {
|
||||
var results = [DownloadedImageUsage]()
|
||||
guard let resultSet = database.executeQuery("SELECT \(Column.url), \(Column.byteCount), \(Column.lastAccessed) FROM \(name) ORDER BY \(Column.lastAccessed);", withArgumentsIn: []) else {
|
||||
return results
|
||||
}
|
||||
defer {
|
||||
resultSet.close()
|
||||
}
|
||||
while resultSet.next() {
|
||||
guard let url = resultSet.string(forColumn: Column.url) else {
|
||||
continue
|
||||
}
|
||||
let lastAccessed = Date(timeIntervalSince1970: resultSet.double(forColumn: Column.lastAccessed))
|
||||
results.append(DownloadedImageUsage(url: url, byteCount: resultSet.long(forColumn: Column.byteCount), lastAccessed: lastAccessed))
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
static func saveAccessDate(url: String, database: FMDatabase) {
|
||||
database.updateRowsWithValue(Date().timeIntervalSince1970, valueKey: Column.lastAccessed, whereKey: Column.url, equals: url, tableName: name)
|
||||
}
|
||||
|
||||
static func delete(urls: [String], database: FMDatabase) {
|
||||
for urlsChunk in urls.chunked(into: maximumURLsPerQuery) {
|
||||
database.deleteRowsWhere(key: Column.url, equalsAnyValue: urlsChunk, tableName: name)
|
||||
}
|
||||
}
|
||||
|
||||
static func save(_ record: DownloadedImageRecord, database: FMDatabase) {
|
||||
let dictionary: DatabaseDictionary = [
|
||||
Column.url: record.url,
|
||||
|
||||
@@ -163,6 +163,30 @@ import RSParser
|
||||
DownloadedImageTable.save(record, database: database)
|
||||
}
|
||||
}
|
||||
|
||||
func saveDownloadedImageAccessDate(url: String) {
|
||||
queue.runInDatabase { database in
|
||||
DownloadedImageTable.saveAccessDate(url: url, database: database)
|
||||
}
|
||||
}
|
||||
|
||||
func fetchDownloadedImageUsageByLeastRecentAccess() async -> [DownloadedImageUsage] {
|
||||
await withCheckedContinuation { continuation in
|
||||
queue.runInDatabase { database in
|
||||
continuation.resume(returning: DownloadedImageTable.fetchUsageByLeastRecentAccess(database: database))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func deleteDownloadedImages(urls: [String]) {
|
||||
guard !urls.isEmpty else {
|
||||
return
|
||||
}
|
||||
urlsUnsuitableForThumbnails.subtract(urls)
|
||||
queue.runInTransaction { database in
|
||||
DownloadedImageTable.delete(urls: urls, database: database)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension ImageMetadataDatabase {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
//
|
||||
// DownloadedImageCacheTests.swift
|
||||
// ImagesTests
|
||||
//
|
||||
// Created by Brent Simmons on 10/26/26.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import Images
|
||||
|
||||
@Suite struct DownloadedImageCacheTests {
|
||||
|
||||
@Test func leastRecentlyUsedImagesAreRemovedDownToTarget() {
|
||||
let now = Date()
|
||||
let longAgo = now.addingTimeInterval(-TimeInterval(days: 10))
|
||||
let urls = ["https://example.com/a.jpg", "https://example.com/b.jpg", "https://example.com/c.jpg", "https://example.com/just-saved.jpg"]
|
||||
let records = [
|
||||
DownloadedImageUsage(url: "https://example.com/no-file.jpg", byteCount: 50, lastAccessed: longAgo),
|
||||
DownloadedImageUsage(url: urls[0], byteCount: 100, lastAccessed: longAgo),
|
||||
DownloadedImageUsage(url: urls[1], byteCount: 100, lastAccessed: longAgo),
|
||||
DownloadedImageUsage(url: urls[2], byteCount: 100, lastAccessed: longAgo),
|
||||
DownloadedImageUsage(url: urls[3], byteCount: 100, lastAccessed: now)
|
||||
]
|
||||
let keys = urls.map { DownloadedImageCache.diskKey($0) }
|
||||
var fileDates = Dictionary(uniqueKeysWithValues: keys.map { ($0, longAgo) })
|
||||
fileDates["unrecorded"] = longAgo
|
||||
fileDates["unrecorded-just-saved"] = now
|
||||
|
||||
let removal = DownloadedImageCache.imageRemoval(records: records, fileDates: fileDates, now: now, limit: .init(maximumByteCount: 350), hardLimit: .init(maximumByteCount: 1000))
|
||||
|
||||
#expect(removal.urls == ["https://example.com/no-file.jpg", urls[0], urls[1]])
|
||||
#expect(removal.keys == ["unrecorded", keys[0], keys[1]])
|
||||
#expect(removal.remainingByteCount == 200)
|
||||
}
|
||||
|
||||
@Test func recentlyUsedImagesAreKeptUnlessOverHardLimit() {
|
||||
let now = Date()
|
||||
let records = (0..<5).map { DownloadedImageUsage(url: "https://example.com/\($0).jpg", byteCount: 100, lastAccessed: now.addingTimeInterval(-TimeInterval(days: 1) + TimeInterval($0))) }
|
||||
let keys = records.map { DownloadedImageCache.diskKey($0.url) }
|
||||
let fileDates = Dictionary(uniqueKeysWithValues: keys.map { ($0, now.addingTimeInterval(-TimeInterval(days: 1))) })
|
||||
|
||||
let underHardLimit = DownloadedImageCache.imageRemoval(records: records, fileDates: fileDates, now: now, limit: .init(maximumByteCount: 200), hardLimit: .init(maximumByteCount: 1000))
|
||||
#expect(underHardLimit.urls.isEmpty)
|
||||
#expect(underHardLimit.remainingByteCount == 500)
|
||||
|
||||
let overHardLimit = DownloadedImageCache.imageRemoval(records: records, fileDates: fileDates, now: now, limit: .init(maximumByteCount: 200), hardLimit: .init(maximumByteCount: 400))
|
||||
#expect(overHardLimit.urls == [records[0].url, records[1].url])
|
||||
#expect(overHardLimit.remainingByteCount == 300)
|
||||
}
|
||||
}
|
||||
@@ -31,12 +31,11 @@ struct CacheCleaner {
|
||||
if flushDate.addingTimeInterval(3600 * 24 * 3) < Date() {
|
||||
let tempDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
|
||||
let faviconsFolderURL = tempDir.appendingPathComponent("Favicons")
|
||||
let downloadedImagesFolderURL = tempDir.appendingPathComponent("DownloadedImages")
|
||||
let feedURLToIconURL = tempDir.appendingPathComponent("FeedURLToIconURLCache.plist")
|
||||
let homePageToIconURL = tempDir.appendingPathComponent("HomePageToIconURLCache.plist")
|
||||
let homePagesWithNoIconURL = tempDir.appendingPathComponent("HomePagesWithNoIconURLCache.plist")
|
||||
|
||||
for tempItem in [faviconsFolderURL, downloadedImagesFolderURL, feedURLToIconURL, homePageToIconURL, homePagesWithNoIconURL] {
|
||||
for tempItem in [faviconsFolderURL, feedURLToIconURL, homePageToIconURL, homePagesWithNoIconURL] {
|
||||
do {
|
||||
logger.info("Removing cache file: \(tempItem.absoluteString)")
|
||||
try FileManager.default.removeItem(at: tempItem)
|
||||
|
||||
Reference in new issue
Block a user