From aafc2bdffd4f43d3e84123204e1edb8f4a0e2545 Mon Sep 17 00:00:00 2001 From: rangaNP Date: Sun, 22 Nov 2026 20:33:27 +0530 Subject: [PATCH] Retry failed favicons and settle cancelled network requests --- Sources/Early/BrowserApplication.swift | 21 +- Sources/EarlyWeb/BoundedResponse.swift | 87 +++-- Sources/EarlyWeb/FaviconStore.swift | 318 ++++++++++++++---- Sources/EarlyWeb/WebViewManager.swift | 1 + Sources/EarlyWeb/WebsiteDataClearing.swift | 9 +- .../HistoryApplicationTests.swift | 19 ++ .../EarlyWebTests/BoundedResponseTests.swift | 82 ++++- .../FaviconAppearanceTests.swift | 2 +- .../EarlyWebTests/FaviconLifecycleTests.swift | 275 +++++++++++++++ Tests/EarlyWebTests/FaviconTests.swift | 16 +- 10 files changed, 702 insertions(+), 128 deletions(-) create mode 100644 Tests/EarlyWebTests/FaviconLifecycleTests.swift diff --git a/Sources/Early/BrowserApplication.swift b/Sources/Early/BrowserApplication.swift index b0d4645..1a39234 100644 --- a/Sources/Early/BrowserApplication.swift +++ b/Sources/Early/BrowserApplication.swift @@ -116,7 +116,6 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { @ObservationIgnored private var pendingRestoredWindows: Set = [] @ObservationIgnored private var profileCleanupTask: Task? @ObservationIgnored private var profileCleanupError: String? - @ObservationIgnored private var profileCleanupIcons: [UUID: [FaviconStore]] = [:] private var primaryWindowIsOpen = false /// Whether the window in front shows a page, for ⌘W's title. SwiftUI /// doesn't observe the key window, and a menu that read it itself kept @@ -643,6 +642,7 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { let since = range.start(now: Date()) return await historyRemoval(for: profile).remove(.since(since), from: history, clearWebsiteData: { [self] in await websiteDataStore(for: profile).removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), modifiedSince: since ?? .distantPast) + await FaviconStore.removeCachedIcons(for: profile, since: since, keeping: sidebarURLs(profileID: profile), ephemeral: testing) }, didChange: { [weak self] in self?.didChangeHistory(profileID: profile) }) } @@ -1122,17 +1122,18 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { return await persistence.flush() } - /// Every tab, pin and Favorite address in the profile's open windows. + /// Every tab, pin and Favorite address in the profile's sidebar. func sidebarURLs(profileID: UUID) -> [URL] { - visibleModels.filter { $0.coordinator.profileID == profileID }.flatMap(\.sidebarURLs) + let models = visibleModels.filter { $0.coordinator.profileID == profileID } + if !models.isEmpty { return models.flatMap(\.sidebarURLs) } + guard let session = workspace?.session(for: profileID) else { return [] } + let tabs = session.tabs + session.additionalWindows.flatMap(\.tabs) + return tabs.flatMap { [$0.currentURL, $0.pinnedURL].compactMap { $0 } } } - /// One window cleared the profile's shared website data; the others drop - /// icons of sites no longer in the sidebar and reload History. + /// Other windows refresh History after the shared website data is cleared. func didClearWebsiteData(profileID: UUID, from source: BrowserWindowModel) { - let kept = sidebarURLs(profileID: profileID) for target in visibleModels where target !== source && target.coordinator.profileID == profileID { - target.webViews.forgetClearedArtwork(keepingIconsFor: kept) target.historyRevision += 1 target.refreshRecentPages() } @@ -1291,8 +1292,6 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { // its windows, credentials, extension data and permissions be removed. workspace = draft profileError = nil - let icons = visibleModels.filter { $0.coordinator.profileID == id }.map { $0.webViews.favicons } - profileCleanupIcons[id] = icons let closing = windows.filter { $0.model.coordinator.profileID == id }.map(\.id) for windowID in closing { nativeWindow(id: windowID)?.close() @@ -1456,9 +1455,7 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { await attempt("Website data") { try await WKWebsiteDataStore.remove(forIdentifier: id) } } await attempt("Website icons") { - for store in profileCleanupIcons[id] ?? [] { await store.shutdown() } - if !testing { try await FaviconStore.removeCache(for: id) } - profileCleanupIcons[id] = nil + try await FaviconStore.removeCache(for: id, ephemeral: testing) } if !failures.isEmpty { throw ProfileCleanupFailure(failures: failures) } } diff --git a/Sources/EarlyWeb/BoundedResponse.swift b/Sources/EarlyWeb/BoundedResponse.swift index 1b4383f..354987c 100644 --- a/Sources/EarlyWeb/BoundedResponse.swift +++ b/Sources/EarlyWeb/BoundedResponse.swift @@ -9,6 +9,13 @@ import Foundation final class BoundedResponse: NSObject, URLSessionDataDelegate, @unchecked Sendable { /// Whether to follow a redirect to the new request. typealias Redirects = @Sendable (HTTPURLResponse, URLRequest) -> Bool + typealias Output = (Data, URLResponse) + + private enum Completion { + case unregistered + case waiting(CheckedContinuation) + case finished(Result) + } private let limit: Int private let redirects: Redirects @@ -16,55 +23,67 @@ final class BoundedResponse: NSObject, URLSessionDataDelegate, @unchecked Sendab private let lock = NSLock() private var body = Data() private var response: URLResponse? - private var continuation: CheckedContinuation<(Data, URLResponse), any Error>? + private var completion = Completion.unregistered + private var exceededLimit = false - private init(limit: Int, redirects: @escaping Redirects) { + init(limit: Int, redirects: @escaping Redirects = { _, _ in true }) { self.limit = limit self.redirects = redirects } static func load(_ request: URLRequest, in session: URLSession, limit: Int, - redirects: @escaping Redirects = { _, _ in true }) async throws -> (Data, URLResponse) { + redirects: @escaping Redirects = { _, _ in true }) async throws -> Output { let reader = BoundedResponse(limit: limit, redirects: redirects) let task = session.dataTask(with: request) task.delegate = reader return try await withTaskCancellationHandler { - try await withCheckedThrowingContinuation { continuation in - reader.lock.withLock { reader.continuation = continuation } - task.resume() - } + try await reader.waitForCompletion(starting: task.resume) } onCancel: { task.cancel() } } - private func finish(_ result: Result<(Data, URLResponse), any Error>) { - let waiting = lock.withLock { () -> CheckedContinuation<(Data, URLResponse), any Error>? in - defer { continuation = nil } - return continuation + func waitForCompletion(starting start: @Sendable () -> Void) async throws -> Output { + try await withCheckedThrowingContinuation { continuation in + let result = lock.withLock { () -> Result? in + switch completion { + case .finished(let result): return result + case .waiting: preconditionFailure("A response can have only one waiter") + case .unregistered: + completion = .waiting(continuation) + return nil + } + } + if let result { continuation.resume(with: result) } + else { start() } } - waiting?.resume(with: result) } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void) { - guard response.expectedContentLength <= limit else { - finish(.failure(URLError(.dataLengthExceedsMaximum))) - completionHandler(.cancel) - return + let allow = lock.withLock { + if case .finished = completion { return false } + guard !exceededLimit else { return false } + exceededLimit = response.expectedContentLength > limit + if exceededLimit { return false } + self.response = response + return true } - lock.withLock { self.response = response } - completionHandler(.allow) + completionHandler(allow ? .allow : .cancel) } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { let tooLong = lock.withLock { () -> Bool in + if case .finished = completion { return false } + guard !exceededLimit else { return false } + if data.count > limit - body.count { + exceededLimit = true + return true + } body.append(data) - return body.count > limit + return false } - guard tooLong else { return } - finish(.failure(URLError(.dataLengthExceedsMaximum))) - dataTask.cancel() + if tooLong { dataTask.cancel() } } func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, @@ -73,12 +92,24 @@ final class BoundedResponse: NSObject, URLSessionDataDelegate, @unchecked Sendab } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: (any Error)?) { - if let error { - finish(.failure(error)) - return + let delivery = lock.withLock { () -> (CheckedContinuation, Result)? in + if case .finished = completion { return nil } + let result: Result + if exceededLimit { result = .failure(URLError(.dataLengthExceedsMaximum)) } + else if let error { result = .failure(error) } + else if let response { result = .success((body, response)) } + else { result = .failure(URLError(.badServerResponse)) } + + // Cancellation can complete before the caller installs its waiter. + // Keep the result and wait for this callback even on size rejection, + // so callers don't free a network slot while the task is cancelling. + let previous = completion + completion = .finished(result) + body = Data() + response = nil + if case .waiting(let waiter) = previous { return (waiter, result) } + return nil } - let (body, response) = lock.withLock { (self.body, self.response) } - guard let response else { finish(.failure(URLError(.badServerResponse))); return } - finish(.success((body, response))) + if let (waiter, result) = delivery { waiter.resume(with: result) } } } diff --git a/Sources/EarlyWeb/FaviconStore.swift b/Sources/EarlyWeb/FaviconStore.swift index 532acac..96dbfdb 100644 --- a/Sources/EarlyWeb/FaviconStore.swift +++ b/Sources/EarlyWeb/FaviconStore.swift @@ -25,6 +25,15 @@ public final class FaviconStore { var cacheIdentifier: String { origin + "#favicon-" + appearance.rawValue } } + private struct Profile: Hashable { + let id: UUID + let ephemeral: Bool + } + + private struct CacheReference { weak var cache: FaviconProfileCache? } + private static var profileCaches: [Profile: CacheReference] = [:] + private static let retryDelays: [Duration] = [.seconds(5), .seconds(15), .seconds(60), .seconds(300)] + public private(set) var appearance: Appearance private var cachedImages: [Key: NSImage] = [:] private var cachedColors: [Key: FaviconColor] = [:] @@ -37,27 +46,52 @@ public final class FaviconStore { @ObservationIgnored private var requests: [Key: Request] = [:] @ObservationIgnored private var order: [Key] = [] @ObservationIgnored private var pending: [Key] = [] - @ObservationIgnored private var running: Set = [] @ObservationIgnored private var tasks: [Key: Task] = [:] @ObservationIgnored private var appearanceObservation: NSKeyValueObservation? @ObservationIgnored private var stopped = false - @ObservationIgnored private let load: @Sendable (String, [URL], Bool) async -> Data? + @ObservationIgnored private let cache: FaviconProfileCache + @ObservationIgnored private let now: () -> ContinuousClock.Instant + @ObservationIgnored private let load: @Sendable (String, [URL], Bool) async -> FaviconLoad private struct Request { + enum State { + case loading + case ready + case failed(retryAt: ContinuousClock.Instant) + } + let token = UUID() let candidates: [URL] let discovered: Bool + var failures = 0 + var state = State.loading } public convenience init(profileID: UUID, ephemeral: Bool = false) { - let directory = ephemeral ? nil : Self.cacheDirectory(for: profileID) - let loader = FaviconLoader(directory: directory) - self.init { key, urls, cached in await loader.load(cacheKey: key, candidates: urls, preferCache: cached) } + let cache = Self.cache(for: profileID, ephemeral: ephemeral) + let loader = cache.loader + self.init(cache: cache, appearance: nil, now: { .now }) { key, urls, cached in + await loader.load(cacheKey: key, candidates: urls, preferCache: cached) + } + } + + convenience init(appearance: Appearance? = nil, now: @escaping () -> ContinuousClock.Instant = { .now }, + profileID: UUID? = nil, ephemeral: Bool = false, + load: @escaping @Sendable (String, [URL], Bool) async -> Data?) { + let cache = profileID.map { Self.cache(for: $0, ephemeral: ephemeral) } ?? FaviconProfileCache(directory: nil) + self.init(cache: cache, appearance: appearance, now: now) { key, urls, cached in + if let data = await load(key, urls, cached) { return .loaded(data) } + return .failed(cached: nil) + } } - init(appearance: Appearance? = nil, load: @escaping @Sendable (String, [URL], Bool) async -> Data?) { + private init(cache: FaviconProfileCache, appearance: Appearance?, now: @escaping () -> ContinuousClock.Instant, + load: @escaping @Sendable (String, [URL], Bool) async -> FaviconLoad) { self.appearance = appearance ?? .current self.load = load + self.cache = cache + self.now = now + cache.add(self) if appearance == nil { appearanceObservation = NSApplication.shared.observe(\.effectiveAppearance) { [weak self] _, _ in Task { @MainActor [weak self] in self?.setAppearance(.current) } @@ -65,6 +99,15 @@ public final class FaviconStore { } } + private static func cache(for profileID: UUID, ephemeral: Bool) -> FaviconProfileCache { + let key = Profile(id: profileID, ephemeral: ephemeral) + if let cache = profileCaches[key]?.cache { return cache } + profileCaches = profileCaches.filter { $0.value.cache != nil } + let cache = FaviconProfileCache(directory: ephemeral ? nil : cacheDirectory(for: profileID)) + profileCaches[key] = CacheReference(cache: cache) + return cache + } + /// Restored pins can switch artwork without opening a page. Live pages /// separately report their newly matching declared icons through WebKit. func setAppearance(_ value: Appearance) { @@ -80,63 +123,60 @@ public final class FaviconStore { .appendingPathComponent("Early/Favicons/\(profileID.uuidString)", isDirectory: true) } - /// Only used after deleting a profile and waiting for its artwork requests. - public nonisolated static func removeCache(for profileID: UUID) async throws { - guard let directory = cacheDirectory(for: profileID) else { return } - try await Task.detached(priority: .utility) { - try ProfileDataCleanup.removeItem(at: directory) - }.value + /// Permanently stops the profile's artwork requests before removing its cache. + public static func removeCache(for profileID: UUID, ephemeral: Bool = false) async throws { + try await cache(for: profileID, ephemeral: ephemeral).remove() } - /// After website data is cleared, forgets artwork for every site except + /// Forgets in-memory artwork for every site except /// those of `pageURLs` (the profile's tabs, pins and Favorites, which keep /// their icons). public func forget(keeping pageURLs: [URL]) { - let kept = Set(pageURLs.compactMap(Self.origin)) - for (key, task) in tasks where !kept.contains(key.origin) { task.cancel() } - tasks = tasks.filter { kept.contains($0.key.origin) } + _ = forget(keeping: Set(pageURLs.compactMap(Self.origin))) + } + + fileprivate func forget(keeping kept: Set) -> [Task] { + // Keep the physical slots until these tasks finish, even when a new + // request for the same key is queued behind a cancelled one. + let cancelled = tasks.compactMap { kept.contains($0.key.origin) ? nil : $0.value } + cancelled.forEach { $0.cancel() } pending.removeAll { !kept.contains($0.origin) } requests = requests.filter { kept.contains($0.key.origin) } - running = running.filter { kept.contains($0.origin) } cachedImages = cachedImages.filter { kept.contains($0.key.origin) } cachedColors = cachedColors.filter { kept.contains($0.key.origin) } order.removeAll { !kept.contains($0.origin) } + return cancelled + } + + func clear(since date: Date?, keeping pageURLs: [URL]) async { + await cache.clear(since: date, keeping: Set(pageURLs.compactMap(Self.origin))) + } + + /// Clears profile artwork even when no browsing window is open. + public static func removeCachedIcons(for profileID: UUID, since date: Date?, keeping pageURLs: [URL], + ephemeral: Bool = false) async { + await cache(for: profileID, ephemeral: ephemeral).clear(since: date, keeping: Set(pageURLs.compactMap(origin))) } - /// Removes this profile's cached icons saved since `date` (nil: all), - /// except those of the sites of `pageURLs`. - public nonisolated static func removeCachedIcons(for profileID: UUID, since date: Date?, keeping pageURLs: [URL]) async { - guard let directory = cacheDirectory(for: profileID) else { return } - let kept = Set(pageURLs.compactMap(origin).flatMap { origin in + fileprivate nonisolated static func fileNames(for origins: Set) -> Set { + Set(origins.flatMap { origin in // Include the old, unclassified file for website-data cleanup; // new loads never reuse it as an arbitrary appearance variant. [FaviconLoader.fileName(for: origin)] + Appearance.allCases.map { FaviconLoader.fileName(for: Key(origin: origin, appearance: $0).cacheIdentifier) } }) - await Task.detached(priority: .utility) { - let files = (try? FileManager.default.contentsOfDirectory(at: directory, - includingPropertiesForKeys: [.contentModificationDateKey])) ?? [] - for file in files where !kept.contains(file.lastPathComponent) { - let modified = (try? file.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantFuture - if date.map({ modified >= $0 }) ?? true { try? FileManager.default.removeItem(at: file) } - } - }.value } public func shutdown() async { + let outstanding = stop() + for task in outstanding { await task.value } + } + + fileprivate func stop() -> [Task] { stopped = true appearanceObservation = nil - let outstanding = Array(tasks.values) - outstanding.forEach { $0.cancel() } - pending.removeAll() - requests.removeAll() - for task in outstanding { await task.value } - tasks.removeAll() - running.removeAll() - cachedImages.removeAll() - cachedColors.removeAll() - order.removeAll() + return forget(keeping: []) } public func image(for url: URL, appearance: Appearance? = nil) -> NSImage? { @@ -149,17 +189,24 @@ public final class FaviconStore { /// Called by visible rows and when a live document's icon selection changes. /// Restored/closed pins only read the cache or request the site's icon file. + /// Failures are retried on demand once their backoff expires. public func request(_ pageURL: URL, discovered: [String]? = nil, appearance: Appearance? = nil) { - guard !stopped, let origin = Self.origin(pageURL) else { return } + guard !stopped, !cache.removed, let origin = Self.origin(pageURL) else { return } let key = Key(origin: origin, appearance: appearance ?? self.appearance) + // Ordinary row updates keep an earlier discovery's candidate list. + if discovered == nil, let previous = requests[key] { + retry(key, previous, explicitly: false) + return + } let candidates = Self.candidates(pageURL: pageURL, discovered: discovered ?? []) let isDiscovered = discovered != nil - if let previous = requests[key] { - guard isDiscovered, !previous.discovered || previous.candidates != candidates else { return } + if let previous = requests[key], previous.discovered == isDiscovered, previous.candidates == candidates { + retry(key, previous, explicitly: false) + return } if requests[key] == nil { // Bound both decoded artwork and negative-cache bookkeeping. - if order.count >= 256, let oldest = order.first(where: { !running.contains($0) && !pending.contains($0) }) { + if order.count >= 256, let oldest = order.first(where: { tasks[$0] == nil && !pending.contains($0) }) { order.removeAll { $0 == oldest } requests.removeValue(forKey: oldest) cachedImages.removeValue(forKey: oldest) @@ -168,38 +215,71 @@ public final class FaviconStore { guard order.count < 256 else { return } order.append(key) } - requests[key] = Request(candidates: candidates, discovered: isDiscovered) + enqueue(key, Request(candidates: candidates, discovered: isDiscovered)) + } + + /// An explicit reload can retry a failed appearance with its known URLs. + func retryFailedIcons(for pageURL: URL) { + guard !stopped, !cache.removed, let origin = Self.origin(pageURL) else { return } + for appearance in Appearance.allCases { + let key = Key(origin: origin, appearance: appearance) + if let previous = requests[key] { retry(key, previous, explicitly: true) } + } + } + + private func retry(_ key: Key, _ request: Request, explicitly: Bool) { + guard case .failed(let retryAt) = request.state, explicitly || now() >= retryAt else { return } + enqueue(key, Request(candidates: request.candidates, discovered: request.discovered, failures: request.failures)) + } + + private func enqueue(_ key: Key, _ request: Request) { + requests[key] = request if !pending.contains(key) { pending.append(key) } drain() } - private func drain() { - guard !stopped else { return } - while running.count < 4, - let index = pending.firstIndex(where: { $0.appearance == appearance && !running.contains($0) }) - ?? pending.firstIndex(where: { !running.contains($0) }) { + fileprivate func drain() { + guard !stopped, !cache.removed, !cache.isClearing else { return } + while tasks.count < 4, + let index = pending.firstIndex(where: { $0.appearance == appearance && tasks[$0] == nil }) + ?? pending.firstIndex(where: { tasks[$0] == nil }) { let key = pending.remove(at: index) guard let request = requests[key] else { continue } - running.insert(key) - let load = load - tasks[key] = Task { [weak self] in - let data = await load(key.cacheIdentifier, request.candidates, !request.discovered) - let color = await Task.detached(priority: .utility) { - data.flatMap { FaviconColor.extract(from: $0) } - }.value - guard let self else { return } - if !Task.isCancelled, self.requests[key]?.token == request.token, - let data, let image = NSImage(data: data) { - self.cachedImages[key] = image - self.cachedColors[key] = color + let load = load, cache = cache + let task = Task { [weak self] in + defer { + cache.finished(request.token) + self?.tasks[key] = nil + self?.drain() } - self.running.remove(key) - self.tasks.removeValue(forKey: key) - self.drain() + let result = await load(key.cacheIdentifier, request.candidates, !request.discovered) + guard !Task.isCancelled, self?.requests[key]?.token == request.token else { return } + let color: FaviconColor? + if let data = result.data { + color = await Task.detached(priority: .utility) { FaviconColor.extract(from: data) }.value + } else { color = nil } + guard let self, !Task.isCancelled, self.requests[key]?.token == request.token else { return } + self.complete(key, request: request, result: result, color: color) } + tasks[key] = task + cache.track(task, token: request.token, origin: key.origin) } } + private func complete(_ key: Key, request: Request, result: FaviconLoad, color: FaviconColor?) { + if let data = result.data, let image = NSImage(data: data) { + cachedImages[key] = image + cachedColors[key] = color + if case .loaded = result { + requests[key]?.state = .ready + return + } + } + let index = min(request.failures, Self.retryDelays.count - 1) + requests[key]?.failures = index + 1 + requests[key]?.state = .failed(retryAt: now().advanced(by: Self.retryDelays[index])) + } + nonisolated static func origin(_ url: URL) -> String? { guard var parts = URLComponents(url: url, resolvingAgainstBaseURL: true), let scheme = parts.scheme?.lowercased(), ["http", "https"].contains(scheme), @@ -229,6 +309,89 @@ public final class FaviconStore { } } +/// Holds the disk writer and clear barrier for all the windows of a profile. +@MainActor +private final class FaviconProfileCache { + private struct StoreReference { weak var store: FaviconStore? } + private struct Load { + let origin: String + let task: Task + } + private var stores: [StoreReference] = [] + // Closing a window releases its pending queue. Keep only the running + // loads here until the loader returns, including any in-progress write. + private var loads: [UUID: Load] = [:] + private let directory: URL? + lazy var loader = FaviconLoader(directory: directory) + private var clearTask: Task? + private var removalTask: Task? + private(set) var removed = false + var isClearing: Bool { clearTask != nil } + + init(directory: URL?) { self.directory = directory } + + func add(_ store: FaviconStore) { + stores.removeAll { $0.store == nil } + stores.append(StoreReference(store: store)) + } + + func track(_ task: Task, token: UUID, origin: String) { + loads[token] = Load(origin: origin, task: task) + } + + func finished(_ token: UUID) { loads[token] = nil } + + private func cancelLoads(keeping kept: Set) -> [Task] { + let affected = loads.values.compactMap { kept.contains($0.origin) ? nil : $0.task } + affected.forEach { $0.cancel() } + return affected + } + + func clear(since date: Date?, keeping kept: Set) async { + // A second caller clears against its own date and kept sites. + while let clearTask { await clearTask.value } + if let removalTask { _ = await removalTask.result; return } + guard !removed else { return } + let task = Task { + for store in stores.compactMap(\.store) { _ = store.forget(keeping: kept) } + let outstanding = cancelLoads(keeping: kept) + for request in outstanding { await request.value } + if directory != nil { await loader.clear(since: date, keeping: kept) } + clearTask = nil + for store in stores.compactMap(\.store) { store.drain() } + } + clearTask = task + await task.value + } + + func remove() async throws { + if let removalTask { return try await removalTask.value } + removed = true + let task = Task { + for store in stores.compactMap(\.store) { _ = store.stop() } + let outstanding = cancelLoads(keeping: []) + for request in outstanding { await request.value } + await clearTask?.value + if directory != nil { try await loader.removeCache() } + } + removalTask = task + defer { removalTask = nil } + try await task.value + } +} + +enum FaviconLoad: Sendable { + case loaded(Data) + case failed(cached: Data?) + + var data: Data? { + switch self { + case .loaded(let data): data + case .failed(let cached): cached + } + } +} + /// Disk access, streaming and bounded image decoding happen off the main actor. actor FaviconLoader { static let byteLimit = 512 * 1024 @@ -248,11 +411,11 @@ actor FaviconLoader { deinit { session.invalidateAndCancel() } - func load(cacheKey: String, candidates: [URL], preferCache: Bool) async -> Data? { + func load(cacheKey: String, candidates: [URL], preferCache: Bool) async -> FaviconLoad { let cached = read(cacheKey) - if preferCache, let cached { return cached } + if preferCache, let cached { return .loaded(cached) } for url in candidates { - guard !Task.isCancelled else { return nil } + guard !Task.isCancelled else { return .failed(cached: nil) } do { var request = URLRequest(url: url) request.httpShouldHandleCookies = false @@ -262,10 +425,25 @@ actor FaviconLoader { guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else { continue } guard !Task.isCancelled, let png = Self.thumbnail(data) else { continue } write(png, origin: cacheKey) - return png + return .loaded(png) } catch { continue } } - return cached + return .failed(cached: cached) + } + + func clear(since date: Date?, keeping origins: Set) { + guard let directory else { return } + let kept = FaviconStore.fileNames(for: origins) + let files = (try? FileManager.default.contentsOfDirectory(at: directory, + includingPropertiesForKeys: [.contentModificationDateKey])) ?? [] + for file in files where !kept.contains(file.lastPathComponent) { + let modified = (try? file.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantFuture + if date.map({ modified >= $0 }) ?? true { try? FileManager.default.removeItem(at: file) } + } + } + + func removeCache() throws { + if let directory { try ProfileDataCleanup.removeItem(at: directory) } } static func thumbnail(_ data: Data) -> Data? { diff --git a/Sources/EarlyWeb/WebViewManager.swift b/Sources/EarlyWeb/WebViewManager.swift index d4c6067..5e71d48 100644 --- a/Sources/EarlyWeb/WebViewManager.swift +++ b/Sources/EarlyWeb/WebViewManager.swift @@ -610,6 +610,7 @@ public final class WebViewManager: NSObject, WKNavigationDelegate, WKUIDelegate public func reload(_ id: UUID) { guard let page = pages[id] else { return } + favicons.retryFailedIcons(for: page.requestedURL) cancelRecovery(id) page.automaticRecoveryAttempted = false page.processTerminated = false diff --git a/Sources/EarlyWeb/WebsiteDataClearing.swift b/Sources/EarlyWeb/WebsiteDataClearing.swift index e37d4c0..96c3a41 100644 --- a/Sources/EarlyWeb/WebsiteDataClearing.swift +++ b/Sources/EarlyWeb/WebsiteDataClearing.swift @@ -11,13 +11,6 @@ extension WebViewManager { public func clearWebsiteData(since date: Date?, keepingIconsFor pages: [URL]) async { await websiteDataStore.removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), modifiedSince: date ?? .distantPast) - if !ephemeral { await FaviconStore.removeCachedIcons(for: profileID, since: date, keeping: pages) } - forgetClearedArtwork(keepingIconsFor: pages) - } - - /// Another window of the profile cleared the shared data. Tab thumbnails - /// belong to open tabs only, so they stay. - public func forgetClearedArtwork(keepingIconsFor pages: [URL]) { - favicons.forget(keeping: pages) + await favicons.clear(since: date, keeping: pages) } } diff --git a/Tests/EarlyBrowserTests/HistoryApplicationTests.swift b/Tests/EarlyBrowserTests/HistoryApplicationTests.swift index 0a13009..f1965b2 100644 --- a/Tests/EarlyBrowserTests/HistoryApplicationTests.swift +++ b/Tests/EarlyBrowserTests/HistoryApplicationTests.swift @@ -220,6 +220,25 @@ import Testing await fixture.cleanup(first, second) } + @Test func clearingFromSettingsWithNoWindowKeepsTheSavedSidebarIcons() async throws { + let fixture = Fixture(), model = try await fixture.start() + let profile = model.coordinator.profileID + let kept = URL(string: "https://kept.invalid")!, removed = URL(string: "https://removed.invalid")! + let pin = try #require(model.coordinator.navigate(to: kept, target: .newTab(spaceID: model.coordinator.activeSpaceID))) + #expect(model.coordinator.setPinned(pin, pinned: true)) + let pixel = Data(base64Encoded: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=")! + let icons = FaviconStore(appearance: .light, profileID: profile, ephemeral: true) { _, _, _ in pixel } + icons.request(kept) + icons.request(removed) + try await wait { icons.image(for: kept) != nil && icons.image(for: removed) != nil } + fixture.app.closeWindow(nil) + #expect(fixture.app.windowModel(nil) == nil) + #expect(await fixture.app.clearHistory(.all, profile: profile)) + #expect(icons.image(for: kept) != nil && icons.image(for: removed) == nil) + await icons.shutdown() + await fixture.cleanup(model) + } + @Test(arguments: [false, true]) func terminationWaitsForAcceptedVisitsEvenAfterTheirWindowClosed(closeWindow: Bool) async throws { let fixture = Fixture(), model = try await fixture.start() diff --git a/Tests/EarlyWebTests/BoundedResponseTests.swift b/Tests/EarlyWebTests/BoundedResponseTests.swift index b1149c6..39a389d 100644 --- a/Tests/EarlyWebTests/BoundedResponseTests.swift +++ b/Tests/EarlyWebTests/BoundedResponseTests.swift @@ -23,9 +23,10 @@ struct BoundedResponseTests { @Test func aLongerBodyStopsAtTheLimitWhetherOrNotItSaysItsLength() async throws { for path in ["/chunks?count=8&size=1000&length=yes", "/chunks?count=200&size=1000"] { - await #expect(throws: URLError.self) { + do { _ = try await BoundedResponse.load(request(path), in: Self.session, limit: 7_999) - } + Issue.record("An oversized response must fail") + } catch let error as URLError { #expect(error.code == .dataLengthExceedsMaximum) } } #expect(ChunkedProtocol.deliveredAfterLimit.value <= 1, "Cancelled as soon as it passed the limit") } @@ -36,6 +37,71 @@ struct BoundedResponseTests { let (data, followed) = try await BoundedResponse.load(request("/redirect"), in: Self.session, limit: 8_000) #expect((followed as? HTTPURLResponse)?.statusCode == 200 && data.count == 1_000) } + + @Test(arguments: [false, true]) + func cancellationBeforeOrDuringWaiterInstallationSettlesExactlyOnce(early: Bool) async throws { + let reader = BoundedResponse(limit: 1_000) + let session = Self.session + let transport = session.dataTask(with: request("/stall")) + defer { transport.cancel() } + let started = Counter() + let cancel: @Sendable () -> Void = { + reader.urlSession(session, task: transport, didCompleteWithError: URLError(.cancelled)) + } + if early { cancel() } + do { + _ = try await reader.waitForCompletion { + started.increment() + // This callback runs during continuation installation, before + // it returns to the awaiting task. Use a different error in + // the early case so dropping the terminal result fails cleanly. + if early { reader.urlSession(session, task: transport, didCompleteWithError: URLError(.timedOut)) } + else { cancel() } + reader.urlSession(session, task: transport, didCompleteWithError: URLError(.badServerResponse)) + } + Issue.record("Cancellation must be returned to the waiter") + } catch let error as URLError { #expect(error.code == .cancelled) } + #expect(started.value == (early ? 0 : 1)) + } + + @Test func cancellingAlreadyCancelledAndActiveTasksAlwaysSettles() async throws { + let session = Self.session, request = request("/stall") + for _ in 0..<20 { + let task = Task { + withUnsafeCurrentTask { $0?.cancel() } + return try await BoundedResponse.load(request, in: session, limit: 1_000) + } + do { + _ = try await task.value + Issue.record("An already-cancelled task must fail") + } catch let error as URLError { #expect(error.code == .cancelled) } + } + let started = ChunkedProtocol.startedStalls.value, stopped = ChunkedProtocol.stoppedStalls.value + let active = Task { try await BoundedResponse.load(request, in: session, limit: 1_000) } + defer { active.cancel() } + try await waitUntil { ChunkedProtocol.startedStalls.value > started } + active.cancel() + do { + _ = try await active.value + Issue.record("An active request must report cancellation") + } catch let error as URLError { #expect(error.code == .cancelled) } + try await waitUntil { ChunkedProtocol.stoppedStalls.value > stopped } + } + + @Test func transportErrorsStayIntact() async throws { + do { + _ = try await BoundedResponse.load(request("/error"), in: Self.session, limit: 1_000) + Issue.record("The transport failure must reach the caller") + } catch let error as URLError { #expect(error.code == .networkConnectionLost) } + } + + private func waitUntil(_ condition: () -> Bool) async throws { + let deadline = ContinuousClock.now.advanced(by: .seconds(10)) + while !condition() { + try #require(ContinuousClock.now < deadline, "The synthetic transport did not signal") + try await Task.sleep(for: .milliseconds(5)) + } + } } /// Sends `count` chunks of `size` bytes, with or without a length, or a redirect. @@ -49,12 +115,17 @@ private final class Counter: @unchecked Sendable { private final class ChunkedProtocol: URLProtocol, @unchecked Sendable { static let deliveredAfterLimit = Counter() + static let startedStalls = Counter() + static let stoppedStalls = Counter() override class func canInit(with request: URLRequest) -> Bool { true } override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + private let lock = NSLock() private var stopped = false override func startLoading() { let url = request.url! + if url.path == "/stall" { Self.startedStalls.increment(); return } + if url.path == "/error" { client?.urlProtocol(self, didFailWithError: URLError(.networkConnectionLost)); return } if url.path == "/redirect" { let response = HTTPURLResponse(url: url, statusCode: 302, httpVersion: "HTTP/1.1", headerFields: ["Location": "https://fixture.invalid/chunks?count=1&size=1000"])! @@ -74,7 +145,7 @@ private final class ChunkedProtocol: URLProtocol, @unchecked Sendable { Self.deliveredAfterLimit.reset() var sent = 0 for _ in 0.. 8_000 { Self.deliveredAfterLimit.increment() } @@ -83,5 +154,8 @@ private final class ChunkedProtocol: URLProtocol, @unchecked Sendable { client?.urlProtocolDidFinishLoading(self) } - override func stopLoading() { stopped = true } + override func stopLoading() { + lock.withLock { stopped = true } + if request.url?.path == "/stall" { Self.stoppedStalls.increment() } + } } diff --git a/Tests/EarlyWebTests/FaviconAppearanceTests.swift b/Tests/EarlyWebTests/FaviconAppearanceTests.swift index e961d69..4e35587 100644 --- a/Tests/EarlyWebTests/FaviconAppearanceTests.swift +++ b/Tests/EarlyWebTests/FaviconAppearanceTests.swift @@ -63,7 +63,7 @@ struct FaviconAppearanceTests { let loader = FaviconLoader(directory: directory) let restored = FaviconStore(appearance: .light) { key, urls, cached in // No network access: both variants must be restored from their own files. - await loader.load(cacheKey: key, candidates: [], preferCache: cached) + await loader.load(cacheKey: key, candidates: [], preferCache: cached).data } restored.request(url) try await waitForFavicon { restored.image(for: url) != nil } diff --git a/Tests/EarlyWebTests/FaviconLifecycleTests.swift b/Tests/EarlyWebTests/FaviconLifecycleTests.swift new file mode 100644 index 0000000..3f911c5 --- /dev/null +++ b/Tests/EarlyWebTests/FaviconLifecycleTests.swift @@ -0,0 +1,275 @@ +// SPDX-License-Identifier: MPL-2.0 + +import AppKit +import EarlyCore +@testable import EarlyWeb +import Testing +import WebKit + +@Suite(.serialized) @MainActor +struct FaviconLifecycleTests { + @Test func failedIconsBackOffWithAnUpperBoundAndKeepTheirDeclaredCandidates() async throws { + let clock = TestClock() + let probe = RetryProbe(successOn: 6) + let store = FaviconStore(appearance: .light, now: clock.read) { _, urls, _ in await probe.load(urls) } + let url = URL(string: "https://fixture.invalid")! + store.request(url, discovered: ["/brand.png"]) + try await waitForFavicon("first failure") { clock.reads == 1 } + for (offset, delay) in [5, 15, 60, 300, 300].enumerated() { + let completed = offset + 1 + clock.advance(.seconds(delay - 1)) + for _ in 0..<20 { store.request(url, discovered: ["/brand.png"]) } + #expect(await probe.paths.count == completed) + + let reads = clock.reads + clock.advance(.seconds(1)) + // A sidebar row supplies no discovered URLs, but retry uses the + // existing declaration rather than starting from /favicon.ico. + for _ in 0..<20 { store.request(url) } + if completed < 5 { + try await waitForFavicon("retry failed after its backoff") { clock.reads > reads + 1 } + } else { + try await waitForFavicon("successful retry") { store.image(for: url) != nil } + } + #expect(await probe.paths.count == completed + 1) + } + #expect(await probe.paths == Array(repeating: "/brand.png", count: 6)) + await store.shutdown() + } + + @Test func reloadRetriesTheUnchangedIconAndKeepsTheWebView() async throws { + _ = NSApplication.shared + let server = try HTMLServer(pages: ["/page": "Test"]) + defer { server.stop() } + let clock = TestClock(), probe = RetryProbe(successOn: 2) + let store = FaviconStore(appearance: .light, now: clock.read) { _, urls, _ in await probe.load(urls) } + let profile = UUID(), url = server.url("/page") + let manager = WebViewManager(profileID: profile, ephemeral: true, faviconStore: store, observesMemoryPressure: false) + defer { manager.discardAll() } + let tab = BrowserTab(spaceID: UUID(), profileID: profile, title: "Test", currentURL: url) + manager.load(url, in: tab) + let page = try #require(manager.pages[tab.id]) + try await waitForFavicon("page and icon failure") { page.loadProgress.phase == .completed && clock.reads > 0 } + #expect(await probe.paths == ["/brand.png"]) + let cycle = page.loadProgress.generation + + manager.reload(tab.id) + try await waitForFavicon("reloaded page and successful icon") { + page.loadProgress.phase == .completed && FaviconStore.Appearance.allCases.contains { + store.image(for: url, appearance: $0) != nil + } + } + #expect(page.loadProgress.generation != cycle && manager.creationCount == 1) + #expect(manager.pages[tab.id] === page) + #expect(await probe.paths == ["/brand.png", "/brand.png"]) + await store.shutdown() + } + + @Test func cancelledLoadsKeepTheirSlotsAndCannotDetachTheReplacement() async throws { + let gate = LoadGate() + defer { Task { await gate.abandon() } } + let store = FaviconStore(appearance: .light) { key, urls, _ in await gate.load(key, urls) } + let old = (0..<4).map { URL(string: "https://old\($0).invalid")! } + let new = (0..<3).map { URL(string: "https://new\($0).invalid")! } + for (index, url) in old.enumerated() { store.request(url, discovered: ["/old-\(index)"]) } + try await waitForFavicon("four loaders started") { await gate.holding.count == 4 } + store.forget(keeping: []) + try await waitForFavicon("asked all four loads to cancel") { await gate.cancelled.count == 4 } + store.request(old[0], discovered: ["/replacement"]) + for (index, url) in new.enumerated() { store.request(url, discovered: ["/new-\(index)"]) } + + await gate.finish("old-1", "old-2", "old-3") + try await waitForFavicon("three independent loads began") { + await gate.holding.isSuperset(of: ["old-0", "new-0", "new-1", "new-2"]) + } + #expect(await !gate.started.contains("replacement")) + await gate.finish("old-0") + try await waitForFavicon("same-key replacement began") { await gate.holding.contains("replacement") } + #expect(await gate.peak == 4) + #expect(store.image(for: old[0]) == nil) + + store.forget(keeping: new) + try await waitForFavicon("replacement is still tracked") { await gate.cancelled.contains("replacement") } + store.request(old[0], discovered: ["/final"]) + await gate.finish("replacement", "new-0", "new-1", "new-2") + try await waitForFavicon("final same-key request") { await gate.holding.contains("final") } + await gate.finish("final") + try await waitForFavicon("replacement artwork installed") { store.image(for: old[0]) != nil } + #expect(await gate.peak == 4) + await store.shutdown() + } + + @Test func profileClearDrainsBothWindowsAndProtectsFreshAndPrivateRequests() async throws { + let profile = UUID(), directory = try #require(FaviconStore.cacheDirectory(for: profile)) + let gate = LoadGate() + defer { + Task { await gate.abandon() } + try? FileManager.default.removeItem(at: directory) + } + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let kept = URL(string: "https://kept.invalid")! + let old = URL(string: "https://old.invalid")!, second = URL(string: "https://second.invalid")! + let keptFiles = [file(for: kept, in: directory), file(for: kept, .light, in: directory), file(for: kept, .dark, in: directory)] + let earlier = file(for: URL(string: "https://earlier.invalid")!, .light, in: directory) + let oldFile = file(for: old, .light, in: directory), secondFile = file(for: second, .dark, in: directory) + for file in keptFiles + [earlier, oldFile, secondFile] { try iconPNG.write(to: file) } + try FileManager.default.setAttributes([.modificationDate: Date(timeIntervalSince1970: 10)], ofItemAtPath: earlier.path) + let firstStore = FaviconStore(appearance: .light, profileID: profile) { key, urls, _ in + if urls.first?.host == kept.host { return iconPNG } + return await gate.load(key, urls, directory: directory) + } + let secondStore = FaviconStore(appearance: .dark, profileID: profile) { key, urls, _ in + await gate.load(key, urls, directory: directory) + } + let privateStore = FaviconStore(appearance: .light, profileID: profile, ephemeral: true) { key, urls, _ in + await gate.load(key, urls) + } + let firstWindow = WebViewManager(profileID: profile, faviconStore: firstStore, + websiteDataStore: .nonPersistent(), observesMemoryPressure: false) + let secondWindow = WebViewManager(profileID: profile, faviconStore: secondStore, + websiteDataStore: firstWindow.websiteDataStore, observesMemoryPressure: false) + firstWindow.favicons.request(kept) + firstWindow.favicons.request(kept, appearance: .dark) + firstWindow.favicons.request(old, discovered: ["/first-old"]) + secondWindow.favicons.request(second, discovered: ["/second-old"]) + privateStore.request(old, discovered: ["/private"]) + try await waitForFavicon("both windows and the private load") { await gate.holding.count == 3 } + try await waitForFavicon("sidebar artwork") { + firstStore.image(for: kept, appearance: .light) != nil && firstStore.image(for: kept, appearance: .dark) != nil + } + var cleared = false + let clear = Task { + await firstWindow.clearWebsiteData(since: Date(timeIntervalSince1970: 20), keepingIconsFor: [kept]) + cleared = true + } + try await waitForFavicon("both old loads cancelled") { + await gate.cancelled.isSuperset(of: ["first-old", "second-old"]) + } + secondWindow.favicons.request(second, discovered: ["/replacement"]) + let newWindow = FaviconStore(appearance: .light, profileID: profile) { key, urls, _ in + await gate.load(key, urls, directory: directory) + } + newWindow.request(old, discovered: ["/new-window"]) + await gate.finish("first-old") + try await waitForFavicon("first delayed write") { await gate.wrote.contains("first-old") } + #expect(!cleared) + #expect(await gate.holding == ["second-old", "private"]) + await gate.finish("second-old") + try await waitForFavicon("profile clear finished") { cleared } + await clear.value + + #expect(await gate.wrote == ["first-old", "second-old"]) + #expect(!FileManager.default.fileExists(atPath: oldFile.path) && !FileManager.default.fileExists(atPath: secondFile.path)) + #expect((keptFiles + [earlier]).allSatisfy { FileManager.default.fileExists(atPath: $0.path) }) + #expect(firstStore.image(for: kept, appearance: .light) != nil && firstStore.image(for: kept, appearance: .dark) != nil) + #expect(await !gate.cancelled.contains("private")) + try await waitForFavicon("fresh requests began after clearing") { + await gate.holding.isSuperset(of: ["replacement", "new-window"]) + } + await gate.finish("replacement", "new-window", "private") + try await waitForFavicon("fresh artwork delivered to each store") { + secondStore.image(for: second) != nil && newWindow.image(for: old) != nil && privateStore.image(for: old) != nil + } + await firstStore.shutdown() + await secondStore.shutdown() + await newWindow.shutdown() + await privateStore.shutdown() + } + + @Test func removingAProfileWaitsForAClosedWindowsWriter() async throws { + let profile = UUID(), directory = try #require(FaviconStore.cacheDirectory(for: profile)) + let gate = LoadGate() + defer { + Task { await gate.abandon() } + try? FileManager.default.removeItem(at: directory) + } + let otherProfile = UUID(), otherDirectory = try #require(FaviconStore.cacheDirectory(for: otherProfile)) + defer { try? FileManager.default.removeItem(at: otherDirectory) } + try FileManager.default.createDirectory(at: otherDirectory, withIntermediateDirectories: true) + let url = URL(string: "https://fixture.invalid")! + let untouched = file(for: url, .light, in: otherDirectory) + try iconPNG.write(to: untouched) + var store: FaviconStore? = FaviconStore(appearance: .light, profileID: profile) { key, urls, _ in + await gate.load(key, urls, directory: directory) + } + weak var releasedStore = store + store?.request(url, discovered: ["/closed"]) + try await waitForFavicon("closed window's request starting") { await gate.holding.contains("closed") } + store = nil + #expect(releasedStore == nil) + let deletion = Task { try await FaviconStore.removeCache(for: profile) } + try await waitForFavicon("closed window's request cancelled") { await gate.cancelled.contains("closed") } + await gate.finish("closed") + try await deletion.value + #expect(await gate.wrote.contains("closed")) + #expect(!FileManager.default.fileExists(atPath: directory.path)) + #expect(FileManager.default.fileExists(atPath: untouched.path)) + } + + private func file(for url: URL, _ appearance: FaviconStore.Appearance? = nil, in directory: URL) -> URL { + let origin = FaviconStore.origin(url)! + let identifier = appearance.map { origin + "#favicon-" + $0.rawValue } ?? origin + return directory.appendingPathComponent(FaviconLoader.fileName(for: identifier)) + } +} + +@MainActor private final class TestClock { + private var instant = ContinuousClock.now + private(set) var reads = 0 + func read() -> ContinuousClock.Instant { reads += 1; return instant } + func advance(_ duration: Duration) { instant = instant.advanced(by: duration) } +} + +private actor RetryProbe { + let successOn: Int + var paths: [String] = [] + init(successOn: Int) { self.successOn = successOn } + func load(_ urls: [URL]) -> Data? { + paths.append(urls.first?.path ?? "") + return paths.count >= successOn ? iconPNG : nil + } +} + +/// Represents a loader already past its last cancellation check. The gate +/// keeps its physical work alive and can still produce a real disk write. +private actor LoadGate { + private var waits: [String: CheckedContinuation] = [:] + private var active = 0 + private var abandoned = false + private(set) var peak = 0 + private(set) var started = Set() + private(set) var cancelled = Set() + private(set) var wrote = Set() + var holding: Set { Set(waits.keys) } + + func load(_ key: String, _ urls: [URL], directory: URL? = nil) async -> Data? { + guard !abandoned, let name = urls.first?.lastPathComponent else { return nil } + active += 1 + peak = max(peak, active) + started.insert(name) + defer { active -= 1 } + await withTaskCancellationHandler { + await withCheckedContinuation { waits[name] = $0 } + } onCancel: { + Task { await self.recordCancellation(name) } + } + guard !abandoned else { return nil } + if let directory { + do { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try iconPNG.write(to: directory.appendingPathComponent(FaviconLoader.fileName(for: key)), options: .atomic) + wrote.insert(name) + } catch { Issue.record("Fixture artwork write failed: \(error)") } + } + return iconPNG + } + + private func recordCancellation(_ name: String) { cancelled.insert(name) } + func finish(_ names: String...) { for name in names { waits.removeValue(forKey: name)?.resume() } } + + func abandon() { + abandoned = true + for continuation in waits.values { continuation.resume() } + waits.removeAll() + } +} diff --git a/Tests/EarlyWebTests/FaviconTests.swift b/Tests/EarlyWebTests/FaviconTests.swift index 54f9f7b..3895d37 100644 --- a/Tests/EarlyWebTests/FaviconTests.swift +++ b/Tests/EarlyWebTests/FaviconTests.swift @@ -6,7 +6,7 @@ import EarlyCore import ImageIO import Testing -private let iconPNG = Data(base64Encoded: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=")! +let iconPNG = Data(base64Encoded: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=")! @Suite struct FaviconTests { @Test @MainActor func candidatesAreBoundedResolvedAndSafe() { @@ -84,14 +84,20 @@ private let iconPNG = Data(base64Encoded: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAA #expect(configuration.httpCookieStorage == nil) #expect(configuration.urlCredentialStorage == nil) let candidates = ["https://fixture.invalid/missing", "https://fixture.invalid/favicon.ico"].map { URL(string: $0)! } - let data = try #require(await loader.load(cacheKey: "https://fixture.invalid", candidates: candidates, preferCache: true)) + let data = try #require(await loader.load(cacheKey: "https://fixture.invalid", candidates: candidates, preferCache: true).data) #expect(FaviconLoader.thumbnail(data) != nil) // New loader / process state can restore the cached icon without a request. let restored = FaviconLoader(directory: directory, configuration: configuration) - #expect(await restored.load(cacheKey: "https://fixture.invalid", candidates: [], preferCache: true) == data) + #expect(await restored.load(cacheKey: "https://fixture.invalid", candidates: [], preferCache: true).data == data) + let fallback = await loader.load(cacheKey: "https://fixture.invalid", candidates: [candidates[0]], preferCache: false) + guard case .failed(let cached) = fallback else { + Issue.record("A failed refresh may keep the old image while remaining eligible for retry") + return + } + #expect(cached == data) let otherProfile = FaviconLoader(directory: directory.appendingPathComponent("other"), configuration: configuration) - #expect(await otherProfile.load(cacheKey: "https://fixture.invalid", candidates: [], preferCache: true) == nil) - #expect(await loader.load(cacheKey: "https://large.invalid", candidates: [URL(string: "https://fixture.invalid/oversized")!], preferCache: false) == nil) + #expect(await otherProfile.load(cacheKey: "https://fixture.invalid", candidates: [], preferCache: true).data == nil) + #expect(await loader.load(cacheKey: "https://large.invalid", candidates: [URL(string: "https://fixture.invalid/oversized")!], preferCache: false).data == nil) } @Test @MainActor func duplicateRequestsAndLateFallbackDoNotReplaceDiscovery() async throws {