diff --git a/Mac/CrashReporter/CrashReporter.swift b/Mac/CrashReporter/CrashReporter.swift index 03f09db8c..7bdbcf2fd 100644 --- a/Mac/CrashReporter/CrashReporter.swift +++ b/Mac/CrashReporter/CrashReporter.swift @@ -59,7 +59,7 @@ import CrashReporter request.httpBody = formData Task { @MainActor in - Downloader.shared.download(request) { _, _, _ in } + Downloader.shared.download(request) { _, _ in } } } diff --git a/Modules/Account/Sources/Account/LocalAccount/InitialFeedDownloader.swift b/Modules/Account/Sources/Account/LocalAccount/InitialFeedDownloader.swift index b7be67956..d31d2380a 100644 --- a/Modules/Account/Sources/Account/LocalAccount/InitialFeedDownloader.swift +++ b/Modules/Account/Sources/Account/LocalAccount/InitialFeedDownloader.swift @@ -16,13 +16,13 @@ struct InitialFeedDownloader { @MainActor static func download(_ url: URL) async throws -> (ParsedFeed?, URLResponse?) { // Route through FeedFinder.downloadAndLog so the fetch shows up in the // activity log alongside the candidate fetches that preceded it. - let (data, response) = try await FeedFinder.downloadAndLog(url) - guard let data else { - return (nil, response) + let downloadResponse = try await FeedFinder.downloadAndLog(url) + guard let data = downloadResponse.data else { + return (nil, downloadResponse.response) } let parserData = ParserData(url: url.absoluteString, data: data) let parsedFeed = try await FeedParser.parse(parserData) - return (parsedFeed, response) + return (parsedFeed, downloadResponse.response) } } diff --git a/Modules/ActivityLog/Sources/ActivityLog/Activity.swift b/Modules/ActivityLog/Sources/ActivityLog/Activity.swift index f05f3d277..87ecb7404 100644 --- a/Modules/ActivityLog/Sources/ActivityLog/Activity.swift +++ b/Modules/ActivityLog/Sources/ActivityLog/Activity.swift @@ -20,6 +20,7 @@ import Foundation public private(set) var endDate: Date? public private(set) var error: (any Error)? public private(set) var completionMessage: String? + public private(set) var returnedFromCache = false /// Hide or show the duration in the UI. public var durationIsSignificant = true @@ -44,10 +45,11 @@ import Foundation state = .running } - func didComplete(_ message: String? = nil) { + func didComplete(_ message: String? = nil, returnedFromCache: Bool = false) { state = .completed endDate = Date() completionMessage = message + self.returnedFromCache = returnedFromCache } func didFail(_ error: any Error) { diff --git a/Modules/ActivityLog/Sources/ActivityLog/ActivityLog.swift b/Modules/ActivityLog/Sources/ActivityLog/ActivityLog.swift index 422236874..e6bb273ef 100644 --- a/Modules/ActivityLog/Sources/ActivityLog/ActivityLog.swift +++ b/Modules/ActivityLog/Sources/ActivityLog/ActivityLog.swift @@ -95,14 +95,14 @@ public extension Notification.Name { /// pending first if it was never explicitly started. Best-effort: does nothing /// if no activity matches. Assumes at most one active activity per /// `(owner, kind)` — for concurrent same-kind work, use the id-based API. - public func didComplete(_ owner: ActivityOwner, kind: ActivityKind, message: String? = nil, durationIsSignificant: Bool = true) { + public func didComplete(_ owner: ActivityOwner, kind: ActivityKind, message: String? = nil, durationIsSignificant: Bool = true, returnedFromCache: Bool = false) { guard let activity = ensureRunning(owner: owner, kind: kind) else { return } activity.durationIsSignificant = durationIsSignificant - activity.didComplete(message) + activity.didComplete(message, returnedFromCache: returnedFromCache) moveToCompleted(activity) postDidChangeNotification() } @@ -139,7 +139,7 @@ public extension Notification.Name { /// Completes the activity with `id`, promoting it from pending first if it was /// never explicitly started. A missing id is a programmer error (asserts). - public func didComplete(id: Int, message: String? = nil, durationIsSignificant: Bool = true) { + public func didComplete(id: Int, message: String? = nil, durationIsSignificant: Bool = true, returnedFromCache: Bool = false) { guard let activity = ensureRunning(id: id) else { assertionFailure("didComplete: no pending or running activity with id \(id)") @@ -147,7 +147,7 @@ public extension Notification.Name { } activity.durationIsSignificant = durationIsSignificant - activity.didComplete(message) + activity.didComplete(message, returnedFromCache: returnedFromCache) moveToCompleted(activity) postDidChangeNotification() } diff --git a/Modules/FeedFinder/Sources/FeedFinder/FeedFinder.swift b/Modules/FeedFinder/Sources/FeedFinder/FeedFinder.swift index 74731d2b7..8afeff4c1 100644 --- a/Modules/FeedFinder/Sources/FeedFinder/FeedFinder.swift +++ b/Modules/FeedFinder/Sources/FeedFinder/FeedFinder.swift @@ -56,7 +56,9 @@ public final class FeedFinder { return (Set([feedSpecifier]), .specialCase) } - let (data, response) = try await downloadAndLog(url) + let downloadResponse = try await downloadAndLog(url) + let data = downloadResponse.data + let response = downloadResponse.response if response?.forcedStatusCode == 404 { if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), urlComponents.host == "micro.blog" { @@ -89,21 +91,15 @@ public final class FeedFinder { return try await FeedFinder.findFeedsInHTMLPage(htmlData: data, urlString: url.absoluteString) } - /// Wraps `Downloader.shared.download(url)` with a per-URL activity entry so - /// the activity log shows every URL that was tried and what came back. - /// HTTP non-2xx is recorded as a *completed* activity (the network call - /// worked, the server returned a status); a thrown error (network failure, - /// timeout, DNS) records as `failed`. - /// - /// Public so callers performing feed-finding-adjacent fetches (e.g. the - /// post-find download that validates the chosen feed) can have their - /// fetches appear in the same Feed Finder activity stream. - public static func downloadAndLog(_ url: URL) async throws -> (Data?, URLResponse?) { + /// Wraps `Downloader.shared.download(url)` with a per-URL activity entry so the + /// fetch shows up in the Feed Finder activity stream. Public so feed-finding-adjacent + /// fetches can join the same stream. + public static func downloadAndLog(_ url: URL) async throws -> DownloadResponse { let id = await activityFetchStart(url: url) do { - let (data, response) = try await Downloader.shared.download(url) - await activityFetchComplete(id: id, data: data, response: response) - return (data, response) + let downloadResponse = try await Downloader.shared.download(url) + await activityFetchComplete(id: id, data: downloadResponse.data, response: downloadResponse.response, returnedFromCache: downloadResponse.returnedFromCache) + return downloadResponse } catch { await activityFetchFail(id: id, error: error) throw error @@ -133,10 +129,9 @@ public final class FeedFinder { return id } - @MainActor private static func activityFetchComplete(id: Int, data: Data?, response: URLResponse?) { + @MainActor private static func activityFetchComplete(id: Int, data: Data?, response: URLResponse?, returnedFromCache: Bool) { let message = fetchCompletionMessage(data: data, response: response) - // A cached fetch can complete in zero seconds; suppress the misleading "(0.00s)". - ActivityLog.shared.didComplete(id: id, message: message, durationIsSignificant: false) + ActivityLog.shared.didComplete(id: id, message: message, durationIsSignificant: !returnedFromCache, returnedFromCache: returnedFromCache) } @MainActor private static func activityFetchFail(id: Int, error: any Error) { @@ -227,8 +222,8 @@ private extension FeedFinder { group.addTask { do { - let (data, response) = try await downloadAndLog(url) - if let data, let response, response.statusIsOK { + let downloadResponse = try await downloadAndLog(url) + if let data = downloadResponse.data, let response = downloadResponse.response, response.statusIsOK { if self.isFeed(data, downloadFeedSpecifier.urlString) { return downloadFeedSpecifier } diff --git a/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataDownloader.swift b/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataDownloader.swift index 514052e64..78fa12057 100644 --- a/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataDownloader.swift +++ b/Modules/HTMLMetadata/Sources/HTMLMetadata/HTMLMetadataDownloader.swift @@ -117,9 +117,9 @@ nonisolated private extension HTMLMetadataDownloader { activityLog.didStart(.htmlMetadataDownloader, kind: kind) do { - let (data, response) = try await Downloader.shared.download(actualURL) + let downloadResponse = try await Downloader.shared.download(actualURL) - if let data, !data.isEmpty, let response, response.statusIsOK { + if let data = downloadResponse.data, !data.isEmpty, let response = downloadResponse.response, response.statusIsOK { let urlToUse = response.url ?? actualURL let parserData = ParserData(url: urlToUse.absoluteString, data: data) let htmlMetadata = HTMLMetadataParser.htmlMetadata(with: parserData) @@ -130,11 +130,11 @@ nonisolated private extension HTMLMetadataDownloader { cacheRecord(record) postNotification(record) - activityLog.didComplete(.htmlMetadataDownloader, kind: kind) + activityLog.didComplete(.htmlMetadataDownloader, kind: kind, returnedFromCache: downloadResponse.returnedFromCache) return } - let statusCode = response?.forcedStatusCode ?? -1 + let statusCode = downloadResponse.response?.forcedStatusCode ?? -1 if (400...499).contains(statusCode) { await HTMLMetadataDatabase.shared.noteFailure(url: url, statusCode: statusCode) } diff --git a/Modules/Images/Sources/Images/ImageDownloader.swift b/Modules/Images/Sources/Images/ImageDownloader.swift index 67aee036a..8b826ffae 100644 --- a/Modules/Images/Sources/Images/ImageDownloader.swift +++ b/Modules/Images/Sources/Images/ImageDownloader.swift @@ -116,9 +116,9 @@ private extension ImageDownloader { } do { - let image = try await downloadImage(url) + let (image, fromCache) = try await downloadImage(url) if let activityOwner, let activityKind { - activityLog.didComplete(activityOwner, kind: activityKind) + activityLog.didComplete(activityOwner, kind: activityKind, returnedFromCache: fromCache) } cacheImage(url, image) ImageMetadataDatabase.shared.clearFailure(url: url) @@ -156,29 +156,28 @@ private extension ImageDownloader { } } - func downloadImage(_ url: String) async throws(ImageDownloadError) -> Data { + func downloadImage(_ url: String) async throws(ImageDownloadError) -> (Data, Bool) { guard let imageURL = URL(string: url) else { throw ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: false) } - let data: Data? - let response: URLResponse? + let downloadResponse: DownloadResponse do { - (data, response) = try await Downloader.shared.download(imageURL) + downloadResponse = try await Downloader.shared.download(imageURL) } catch { Self.logger.error("Error downloading image at \(url) \(error.localizedDescription)") throw ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: true) } - if let data, !data.isEmpty, let response, response.statusIsOK { + if let data = downloadResponse.data, !data.isEmpty, let response = downloadResponse.response, response.statusIsOK { let scaledData = RSImage.scaledImageData(data, maxPixelSize: RSImage.maxIconPixelSize) ?? data saveToDisk(url, scaledData) - return scaledData + return (scaledData, downloadResponse.returnedFromCache) } - let statusCode = (response as? HTTPURLResponse)?.statusCode + let statusCode = (downloadResponse.response as? HTTPURLResponse)?.statusCode // 2xx with empty / missing body — server said OK but gave us no image bytes. - if let response, response.statusIsOK { + if let response = downloadResponse.response, response.statusIsOK { throw ImageDownloadError(statusCode: statusCode, decodingFailed: true, isTransient: false) } let isTransient = statusCode.map { (500...599).contains($0) } ?? true diff --git a/Modules/Images/Sources/Images/SingleFaviconDownloader.swift b/Modules/Images/Sources/Images/SingleFaviconDownloader.swift index 60ca56705..37cd8a7b1 100644 --- a/Modules/Images/Sources/Images/SingleFaviconDownloader.swift +++ b/Modules/Images/Sources/Images/SingleFaviconDownloader.swift @@ -145,17 +145,16 @@ private extension SingleFaviconDownloader { activityLog.createActivity(owner: .faviconDownloader, kind: kind, detail: homePageURL) activityLog.didStart(.faviconDownloader, kind: kind) - let data: Data? - let response: URLResponse? + let downloadResponse: DownloadResponse do { - (data, response) = try await Downloader.shared.download(url) + downloadResponse = try await Downloader.shared.download(url) } catch { Self.logger.error("Error downloading image at \(url.absoluteString): \(error.localizedDescription)") activityLog.didFail(.faviconDownloader, kind: kind, error: error) throw ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: true) } - if let data, !data.isEmpty, let response, response.statusIsOK { + if let data = downloadResponse.data, !data.isEmpty, let response = downloadResponse.response, response.statusIsOK { let scaledData = RSImage.scaledImageData(data, maxPixelSize: RSImage.maxIconPixelSize) ?? data let image = await RSImage.image(data: scaledData) guard let image else { @@ -165,13 +164,13 @@ private extension SingleFaviconDownloader { throw error } saveToDisk(scaledData) - activityLog.didComplete(.faviconDownloader, kind: kind) + activityLog.didComplete(.faviconDownloader, kind: kind, returnedFromCache: downloadResponse.returnedFromCache) return image } - let statusCode = (response as? HTTPURLResponse)?.statusCode + let statusCode = (downloadResponse.response as? HTTPURLResponse)?.statusCode // 2xx with empty / missing body — server said OK but gave us no image bytes. - if let response, response.statusIsOK { + if let response = downloadResponse.response, response.statusIsOK { let error = ImageDownloadError(statusCode: statusCode, decodingFailed: true, isTransient: false) activityLog.didFail(.faviconDownloader, kind: kind, error: error) throw error diff --git a/Modules/RSWeb/Sources/RSWeb/DownloadResponse.swift b/Modules/RSWeb/Sources/RSWeb/DownloadResponse.swift new file mode 100644 index 000000000..4012e0dd2 --- /dev/null +++ b/Modules/RSWeb/Sources/RSWeb/DownloadResponse.swift @@ -0,0 +1,25 @@ +// +// DownloadResponse.swift +// RSWeb +// +// Created by Brent Simmons on 6/17/26. +// + +import Foundation + +/// The result of a successful `Downloader` download. +public struct DownloadResponse: Sendable { + + public let data: Data? + public let response: URLResponse? + + /// True when served without a network request — from the short-term cache + /// or by coalescing onto an in-progress download for the same URL. + public let returnedFromCache: Bool + + public init(data: Data?, response: URLResponse?, returnedFromCache: Bool) { + self.data = data + self.response = response + self.returnedFromCache = returnedFromCache + } +} diff --git a/Modules/RSWeb/Sources/RSWeb/Downloader.swift b/Modules/RSWeb/Sources/RSWeb/Downloader.swift index 689e99101..dac4fad84 100755 --- a/Modules/RSWeb/Sources/RSWeb/Downloader.swift +++ b/Modules/RSWeb/Sources/RSWeb/Downloader.swift @@ -10,7 +10,7 @@ import Foundation import os import RSCore -public typealias DownloadCallback = @MainActor (Data?, URLResponse?, Error?) -> Swift.Void +public typealias DownloadCallback = @MainActor (DownloadResponse, Error?) -> Swift.Void /// Simple downloader, for a one-shot download like an image /// or a web page. For a download-feeds session, see DownloadSession. @@ -18,7 +18,7 @@ public typealias DownloadCallback = @MainActor (Data?, URLResponse?, Error?) -> @MainActor public final class Downloader { public static let shared = Downloader() private let urlSession: URLSession - private var callbacks = [URL: [DownloadCallback]]() + private var callbacks = [URL: [(callback: DownloadCallback, fromCache: Bool)]]() private let cache = DownloadCache.shared nonisolated private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "Downloader") @@ -42,13 +42,13 @@ public typealias DownloadCallback = @MainActor (Data?, URLResponse?, Error?) -> urlSession.invalidateAndCancel() } - public func download(_ url: URL) async throws -> (Data?, URLResponse?) { + public func download(_ url: URL) async throws -> DownloadResponse { try await withCheckedThrowingContinuation { continuation in - download(url) { data, response, error in + download(url) { downloadResponse, error in if let error { continuation.resume(throwing: error) } else { - continuation.resume(returning: (data, response)) + continuation.resume(returning: downloadResponse) } } } @@ -69,7 +69,7 @@ public typealias DownloadCallback = @MainActor (Data?, URLResponse?, Error?) -> guard url.isHTTPOrHTTPSURL() else { Self.logger.debug("Downloader: skipping download for non-http/https URL: \(url)") - callback(nil, nil, nil) + callback(DownloadResponse(data: nil, response: nil, returnedFromCache: false), nil) return } @@ -79,7 +79,7 @@ public typealias DownloadCallback = @MainActor (Data?, URLResponse?, Error?) -> if isCacheableRequest { if let cachedRecord = cache[url.absoluteString] { Self.logger.debug("Downloader: returning cached record for \(url)") - callback(cachedRecord.data, cachedRecord.response, nil) + callback(DownloadResponse(data: cachedRecord.data, response: cachedRecord.response, returnedFromCache: true), nil) return } } @@ -87,12 +87,13 @@ public typealias DownloadCallback = @MainActor (Data?, URLResponse?, Error?) -> // Add callback. If there is already a download in progress for this URL, return early. if callbacks[url] == nil { Self.logger.debug("Downloader: downloading \(url)") - callbacks[url] = [callback] + callbacks[url] = [(callback, false)] } else { - // A download is already be in progress for this URL. Don’t start a separate download. - // Add the callback to the callbacks array for this URL. + // A download is already in progress for this URL. Don’t start a separate download. + // Add the callback to the callbacks array for this URL. This caller is coalesced + // onto the in-progress download, so it makes no network request of its own. Self.logger.debug("Downloader: download in progress for \(url) — adding callback") - callbacks[url]?.append(callback) + callbacks[url]?.append((callback, true)) return } @@ -136,8 +137,9 @@ private extension Downloader { Self.logger.debug("Downloader: calling \(count) callbacks for URL \(url)") } - for callback in callbacksForURL { - callback(data, response, error) + for entry in callbacksForURL { + let downloadResponse = DownloadResponse(data: data, response: response, returnedFromCache: entry.fromCache) + entry.callback(downloadResponse, error) } } } diff --git a/Shared/ActivityLog/ActivityLogViewModel.swift b/Shared/ActivityLog/ActivityLogViewModel.swift index f93e3693a..d51d4cb6d 100644 --- a/Shared/ActivityLog/ActivityLogViewModel.swift +++ b/Shared/ActivityLog/ActivityLogViewModel.swift @@ -57,6 +57,11 @@ struct ActivityLogTextSegment { result.append(ActivityLogTextSegment(text: " — \(message)", color: .secondary, weight: .regular)) } + if activity.returnedFromCache { + let fromCacheText = NSLocalizedString("from cache", comment: "Activity log — appended when a download was served from cache instead of the network") + result.append(ActivityLogTextSegment(text: " — \(fromCacheText)", color: .secondary, weight: .regular)) + } + if isFailed, let error = activity.error { result.append(ActivityLogTextSegment(text: " — \(error.localizedDescription)", color: .failure, weight: .regular)) } diff --git a/Shared/Localizable.xcstrings b/Shared/Localizable.xcstrings index 2753e4c5b..17519a2fa 100644 --- a/Shared/Localizable.xcstrings +++ b/Shared/Localizable.xcstrings @@ -451,6 +451,9 @@ "Folders" : { "comment" : "Folders" }, + "from cache" : { + "comment" : "Activity log — appended when a download was served from cache instead of the network" + }, "General" : { "comment" : "Preferences" }, diff --git a/iOS/Article/WebViewController.swift b/iOS/Article/WebViewController.swift index 1dee7125d..d21e34cad 100644 --- a/iOS/Article/WebViewController.swift +++ b/iOS/Article/WebViewController.swift @@ -696,8 +696,8 @@ private extension WebViewController { guard let imageURL = URL(string: clickMessage.imageURL) else { return } - Downloader.shared.download(imageURL) { [weak self] data, _, error in - guard let self, let data, error == nil, !data.isEmpty, + Downloader.shared.download(imageURL) { [weak self] downloadResponse, error in + guard let self, let data = downloadResponse.data, error == nil, !data.isEmpty, let image = UIImage(data: data) else { return }