Get sizes from disk.

This commit is contained in:
Brent Simmons committed 2026-11-02 10:25:00 -08:00
1 parent feedf2913d
commit 3ec25f165e
6 files changed
+75 -51

No files matched your search

@@ -344,7 +344,7 @@ private extension DownloadedImageCache {
conditionalGetInfo = HTTPConditionalGetInfo(urlResponse: httpResponse)
}
let nextCheck = Self.nextCheck(httpResponse, hasValidators: conditionalGetInfo != nil)
ImageDatabase.shared.saveDownloadedImage(DownloadedImageRecord(url: url, byteCount: data.count, pixelSize: pixelSize, conditionalGetInfo: conditionalGetInfo, nextCheck: nextCheck))
ImageDatabase.shared.saveDownloadedImage(DownloadedImageRecord(url: url, pixelSize: pixelSize, conditionalGetInfo: conditionalGetInfo, nextCheck: nextCheck))
return true
}
@@ -391,8 +391,8 @@ private extension DownloadedImageCache {
// MARK: - Removing Images
/// Removes the least recently used images until the total is `maximumStoredByteCount`.
/// Also removes files with no record and records with no file, so the total matches the disk.
/// Removes the least recently used images until their files total `maximumStoredByteCount`.
/// Also removes files with no record and records with no file.
func removeImagesOverSizeLimit() async {
let startDate = Date()
@@ -400,11 +400,11 @@ private extension DownloadedImageCache {
Self.logger.error("Skipped removing images: couldn’t read the image records.")
return
}
guard let fileDates = await Self.fileModificationDates(diskCache) else {
guard let files = await Self.storedFiles(diskCache) else {
Self.logger.error("Skipped removing images: couldn’t list the images folder.")
return
}
let removal = await Self.imageRemoval(records: records, fileDates: fileDates, urlsInUse: Set(tasks.keys), now: startDate, maximumByteCount: Self.maximumStoredByteCount)
let removal = await Self.imageRemoval(records: records, files: files, urlsInUse: Set(tasks.keys), now: startDate, maximumByteCount: Self.maximumStoredByteCount)
guard !removal.urls.isEmpty || !removal.keys.isEmpty else {
return
@@ -441,17 +441,24 @@ private extension DownloadedImageCache {
extension DownloadedImageCache {
struct StoredFile: Equatable, Sendable {
let modificationDate: Date
let byteCount: Int
}
/// Keys are file names. Nil when the folder can’t be listed.
@concurrent static func fileModificationDates(_ diskCache: BinaryDiskCache) async -> [String: Date]? {
@concurrent static func storedFiles(_ diskCache: BinaryDiskCache) async -> [String: StoredFile]? {
let folderURL = URL(fileURLWithPath: diskCache.folder)
guard let fileURLs = try? FileManager.default.contentsOfDirectory(at: folderURL, includingPropertiesForKeys: [.contentModificationDateKey]) else {
let resourceKeys: Set<URLResourceKey> = [.contentModificationDateKey, .fileSizeKey]
guard let fileURLs = try? FileManager.default.contentsOfDirectory(at: folderURL, includingPropertiesForKeys: Array(resourceKeys)) else {
return nil
}
var fileDates = [String: Date]()
var files = [String: StoredFile]()
for fileURL in fileURLs {
fileDates[fileURL.lastPathComponent] = (try? fileURL.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate ?? .distantPast
let resourceValues = try? fileURL.resourceValues(forKeys: resourceKeys)
files[fileURL.lastPathComponent] = StoredFile(modificationDate: resourceValues?.contentModificationDate ?? .distantPast, byteCount: resourceValues?.fileSize ?? 0)
}
return fileDates
return files
}
nonisolated static func diskKey(_ url: String) -> String {
@@ -506,36 +513,36 @@ extension DownloadedImageCache {
/// the least recently accessed images are removed.
/// Nothing changed in the last minute is removed, since it may be in the middle of being saved.
/// Images in `urlsInUse` are being read or downloaded, so they’re kept too.
@concurrent static func imageRemoval(records: [DownloadedImageUsage], fileDates: [String: Date], urlsInUse: Set<String>, now: Date, maximumByteCount: Int) async -> ImageRemoval {
@concurrent static func imageRemoval(records: [DownloadedImageUsage], files: [String: StoredFile], urlsInUse: Set<String>, now: Date, maximumByteCount: Int) async -> ImageRemoval {
let recentChangeDate = now.addingTimeInterval(-recentChangeInterval)
var recordsToKeep = [(record: DownloadedImageUsage, key: String)]()
var recordsToKeep = [(record: DownloadedImageUsage, key: String, byteCount: Int)]()
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 {
if files[key] == nil && record.lastAccessed < recentChangeDate {
urls.append(record.url)
} else {
recordsToKeep.append((record: record, key: key))
recordsToKeep.append((record: record, key: key, byteCount: files[key]?.byteCount ?? 0))
}
}
var keys = Set(fileDates.filter { !recordedKeys.contains(baseDiskKey($0.key)) && $0.value < recentChangeDate }.keys)
var byteCount = recordsToKeep.reduce(0) { $0 + $1.record.byteCount }
var keys = Set(files.filter { !recordedKeys.contains(baseDiskKey($0.key)) && $0.value.modificationDate < recentChangeDate }.keys)
var byteCount = recordsToKeep.reduce(0) { $0 + $1.byteCount }
for (record, key) in recordsToKeep where !urlsInUse.contains(record.url) {
for (record, key, recordByteCount) in recordsToKeep where !urlsInUse.contains(record.url) {
if byteCount <= maximumByteCount || record.lastAccessed >= recentChangeDate {
break
}
urls.append(record.url)
keys.insert(key)
byteCount -= record.byteCount
byteCount -= recordByteCount
}
// Derived copies go with their images.
let removedKeys = keys.union(urls.map(diskKey))
keys.formUnion(fileDates.keys.filter { baseDiskKey($0) != $0 && removedKeys.contains(baseDiskKey($0)) })
keys.formUnion(files.keys.filter { baseDiskKey($0) != $0 && removedKeys.contains(baseDiskKey($0)) })
return ImageRemoval(urls: urls, keys: keys, remainingByteCount: byteCount)
}
@@ -14,7 +14,6 @@ import RSDatabaseObjC
/// A copy stored by `DownloadedImageCache`. `pixelSize` is nil when ImageIO can’t read the image.
struct DownloadedImageRecord: Sendable {
let url: String
let byteCount: Int
let pixelSize: (width: Int, height: Int)?
let conditionalGetInfo: HTTPConditionalGetInfo?
let nextCheck: Date
@@ -29,7 +28,6 @@ struct DownloadedImageValidation: Sendable {
/// What `DownloadedImageCache` needs to choose images to remove.
struct DownloadedImageUsage: Sendable {
let url: String
let byteCount: Int
let lastAccessed: Date
}
@@ -40,7 +38,6 @@ struct DownloadedImageTable {
private struct Column {
static let url = "url"
static let byteCount = "byteCount"
static let pixelWidth = "pixelWidth"
static let pixelHeight = "pixelHeight"
static let lastAccessed = "lastAccessed"
@@ -77,7 +74,7 @@ struct DownloadedImageTable {
/// Least recently accessed first. Nil when the query fails.
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 {
guard let resultSet = database.executeQuery("SELECT \(Column.url), \(Column.lastAccessed) FROM \(name) ORDER BY \(Column.lastAccessed);", withArgumentsIn: []) else {
return nil
}
defer {
@@ -88,7 +85,7 @@ struct DownloadedImageTable {
continue
}
let lastAccessed = Date(timeIntervalSince1970: resultSet.double(forColumn: Column.lastAccessed))
results.append(DownloadedImageUsage(url: url, byteCount: resultSet.long(forColumn: Column.byteCount), lastAccessed: lastAccessed))
results.append(DownloadedImageUsage(url: url, lastAccessed: lastAccessed))
}
return results
}
@@ -125,7 +122,6 @@ struct DownloadedImageTable {
static func save(_ record: DownloadedImageRecord, database: FMDatabase) {
let dictionary: DatabaseDictionary = [
Column.url: record.url,
Column.byteCount: record.byteCount,
Column.pixelWidth: record.pixelSize?.width as Any,
Column.pixelHeight: record.pixelSize?.height as Any,
Column.lastAccessed: Date().timeIntervalSince1970,
@@ -35,7 +35,7 @@ import RSParser
CREATE TABLE IF NOT EXISTS downloadFailure (url TEXT PRIMARY KEY NOT NULL, lastChecked REAL NOT NULL);
CREATE TABLE IF NOT EXISTS homePageFavicon (homePageURL TEXT PRIMARY KEY NOT NULL, faviconURL TEXT, lastChecked REAL NOT NULL);
CREATE TABLE IF NOT EXISTS feedIconURL (feedURL TEXT PRIMARY KEY NOT NULL, iconURL TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS downloadedImage (url TEXT PRIMARY KEY NOT NULL, byteCount INTEGER NOT NULL, pixelWidth INTEGER, pixelHeight INTEGER, lastAccessed REAL NOT NULL, etag TEXT, lastModified TEXT, nextCheck REAL NOT NULL);
CREATE TABLE IF NOT EXISTS downloadedImage (url TEXT PRIMARY KEY NOT NULL, pixelWidth INTEGER, pixelHeight INTEGER, lastAccessed REAL NOT NULL, etag TEXT, lastModified TEXT, nextCheck REAL NOT NULL);
"""
/// Development builds created this table.
@@ -55,7 +55,7 @@ private typealias ArticleAttachment = Articles.Attachment
let finder = ArticleThumbnailFinder(imageDatabase: imageDatabase)
let article = makeArticle(imageURL: "https://example.com/image.jpg", thumbnailURL: "https://example.com/logo.png")
imageDatabase.saveDownloadedImage(DownloadedImageRecord(url: "https://example.com/logo.png", byteCount: 1024, pixelSize: (width: 48, height: 48), conditionalGetInfo: nil, nextCheck: Date()))
imageDatabase.saveDownloadedImage(DownloadedImageRecord(url: "https://example.com/logo.png", pixelSize: (width: 48, height: 48), conditionalGetInfo: nil, nextCheck: Date()))
#expect(finder.thumbnailURL(for: article, mode: .small) == "https://example.com/image.jpg")
#expect(!imageDatabase.recentlyFailed(url: "https://example.com/logo.png"))
@@ -17,18 +17,18 @@ import RSCore
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)
DownloadedImageUsage(url: "https://example.com/no-file.jpg", lastAccessed: longAgo),
DownloadedImageUsage(url: urls[0], lastAccessed: longAgo),
DownloadedImageUsage(url: urls[1], lastAccessed: longAgo),
DownloadedImageUsage(url: urls[2], lastAccessed: longAgo),
DownloadedImageUsage(url: urls[3], lastAccessed: now)
]
let keys = urls.map { DownloadedImageCache.diskKey($0) }
var fileDates = Dictionary(uniqueKeysWithValues: keys.map { ($0, longAgo) })
fileDates["unrecorded"] = longAgo
fileDates["unrecordedJustSaved"] = now
var files = Dictionary(uniqueKeysWithValues: keys.map { ($0, storedFile(longAgo, byteCount: 100)) })
files["unrecorded"] = storedFile(longAgo, byteCount: 100)
files["unrecordedJustSaved"] = storedFile(now, byteCount: 100)
let removal = await DownloadedImageCache.imageRemoval(records: records, fileDates: fileDates, urlsInUse: [], now: now, maximumByteCount: 350)
let removal = await DownloadedImageCache.imageRemoval(records: records, files: files, urlsInUse: [], now: now, maximumByteCount: 350)
#expect(removal.urls == ["https://example.com/no-file.jpg", urls[0]])
#expect(removal.keys == ["unrecorded", keys[0]])
@@ -38,10 +38,10 @@ import RSCore
@Test func imagesInUseAreKept() async {
let now = Date()
let longAgo = now.addingTimeInterval(-TimeInterval(days: 10))
let records = (0..<3).map { DownloadedImageUsage(url: "https://example.com/\($0).jpg", byteCount: 100, lastAccessed: longAgo) }
let fileDates = Dictionary(uniqueKeysWithValues: records.map { (DownloadedImageCache.diskKey($0.url), longAgo) })
let records = (0..<3).map { DownloadedImageUsage(url: "https://example.com/\($0).jpg", lastAccessed: longAgo) }
let files = Dictionary(uniqueKeysWithValues: records.map { (DownloadedImageCache.diskKey($0.url), storedFile(longAgo, byteCount: 100)) })
let removal = await DownloadedImageCache.imageRemoval(records: records, fileDates: fileDates, urlsInUse: [records[0].url], now: now, maximumByteCount: 200)
let removal = await DownloadedImageCache.imageRemoval(records: records, files: files, urlsInUse: [records[0].url], now: now, maximumByteCount: 200)
#expect(removal.urls == [records[1].url])
#expect(removal.remainingByteCount == 200)
@@ -50,26 +50,40 @@ import RSCore
@Test func derivedCopiesAreKeptAndRemovedWithTheirImages() async {
let now = Date()
let longAgo = now.addingTimeInterval(-TimeInterval(days: 10))
let records = (0..<2).map { DownloadedImageUsage(url: "https://example.com/\($0).png", byteCount: 100, lastAccessed: longAgo.addingTimeInterval(TimeInterval($0))) }
let records = (0..<2).map { DownloadedImageUsage(url: "https://example.com/\($0).png", lastAccessed: longAgo.addingTimeInterval(TimeInterval($0))) }
let removedCopy = DownloadedImageCache.derivedDiskKey(records[0].url, suffix: "144")
let keptCopy = DownloadedImageCache.derivedDiskKey(records[1].url, suffix: "144")
let orphanedCopy = DownloadedImageCache.derivedDiskKey("https://example.com/gone.png", suffix: "144")
var fileDates = Dictionary(uniqueKeysWithValues: records.map { (DownloadedImageCache.diskKey($0.url), longAgo) })
var files = Dictionary(uniqueKeysWithValues: records.map { (DownloadedImageCache.diskKey($0.url), storedFile(longAgo, byteCount: 100)) })
for key in [removedCopy, keptCopy, orphanedCopy] {
fileDates[key] = longAgo
files[key] = storedFile(longAgo, byteCount: 10)
}
let removal = await DownloadedImageCache.imageRemoval(records: records, fileDates: fileDates, urlsInUse: [], now: now, maximumByteCount: 150)
let removal = await DownloadedImageCache.imageRemoval(records: records, files: files, urlsInUse: [], now: now, maximumByteCount: 150)
#expect(removal.urls == [records[0].url])
#expect(removal.keys == [DownloadedImageCache.diskKey(records[0].url), removedCopy, orphanedCopy])
#expect(removal.remainingByteCount == 100)
}
@Test func folderThatCantBeListedHasNoFileDates() async {
@Test func folderThatCantBeListedHasNoStoredFiles() async {
let missingFolder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString).path
let fileDates = await DownloadedImageCache.fileModificationDates(BinaryDiskCache(folder: missingFolder))
#expect(fileDates == nil)
let files = await DownloadedImageCache.storedFiles(BinaryDiskCache(folder: missingFolder))
#expect(files == nil)
}
@Test func storedFilesHaveTheirSizesOnDisk() async throws {
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("DownloadedImageCacheTests-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
defer {
try? FileManager.default.removeItem(at: folder)
}
let diskCache = BinaryDiskCache(folder: folder.path)
let key = DownloadedImageCache.diskKey("https://example.com/photo.jpg")
try diskCache.setData(Data(count: 1234), forKey: key)
let files = await DownloadedImageCache.storedFiles(diskCache)
#expect(files?[key]?.byteCount == 1234)
}
@Test func shortMaxAgeIsRaisedToThreeDays() throws {
@@ -108,3 +122,10 @@ import RSCore
#expect(retryDateAfterLaterFailure == retryDateFromRetryAfter)
}
}
private extension DownloadedImageCacheTests {
func storedFile(_ modificationDate: Date, byteCount: Int) -> DownloadedImageCache.StoredFile {
DownloadedImageCache.StoredFile(modificationDate: modificationDate, byteCount: byteCount)
}
}
@@ -83,11 +83,11 @@ import RSWeb
let conditionalGetInfo = try #require(HTTPConditionalGetInfo(lastModified: nil, etag: "\"abc\""))
let imageDatabase = ImageDatabase(databasePath: databasePath)
imageDatabase.saveDownloadedImage(DownloadedImageRecord(url: iconURL, byteCount: 100, pixelSize: (width: 48, height: 48), conditionalGetInfo: nil, nextCheck: nextCheck))
imageDatabase.saveDownloadedImage(DownloadedImageRecord(url: replacedIconURL, byteCount: 100, pixelSize: (width: 48, height: 48), conditionalGetInfo: nil, nextCheck: nextCheck))
imageDatabase.saveDownloadedImage(DownloadedImageRecord(url: replacedIconURL, byteCount: 200, pixelSize: (width: 512, height: 512), conditionalGetInfo: nil, nextCheck: nextCheck))
imageDatabase.saveDownloadedImage(DownloadedImageRecord(url: photoURL, byteCount: 300, pixelSize: (width: 800, height: 600), conditionalGetInfo: conditionalGetInfo, nextCheck: nextCheck))
imageDatabase.saveDownloadedImage(DownloadedImageRecord(url: unreadableImageURL, byteCount: 400, pixelSize: nil, conditionalGetInfo: nil, nextCheck: nextCheck))
imageDatabase.saveDownloadedImage(DownloadedImageRecord(url: iconURL, pixelSize: (width: 48, height: 48), conditionalGetInfo: nil, nextCheck: nextCheck))
imageDatabase.saveDownloadedImage(DownloadedImageRecord(url: replacedIconURL, pixelSize: (width: 48, height: 48), conditionalGetInfo: nil, nextCheck: nextCheck))
imageDatabase.saveDownloadedImage(DownloadedImageRecord(url: replacedIconURL, pixelSize: (width: 512, height: 512), conditionalGetInfo: nil, nextCheck: nextCheck))
imageDatabase.saveDownloadedImage(DownloadedImageRecord(url: photoURL, pixelSize: (width: 800, height: 600), conditionalGetInfo: conditionalGetInfo, nextCheck: nextCheck))
imageDatabase.saveDownloadedImage(DownloadedImageRecord(url: unreadableImageURL, pixelSize: nil, conditionalGetInfo: nil, nextCheck: nextCheck))
let validation = await imageDatabase.fetchDownloadedImageValidation(url: photoURL)
#expect(validation?.conditionalGetInfo == conditionalGetInfo)