From 86e69b5899b141bb40614aa008234a21d318da35 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Fri, 4 Sep 2026 10:57:11 -0700 Subject: [PATCH 01/25] Await push-triggered syncs instead of doing fire-and-forget. --- Modules/Account/Sources/Account/AccountManager.swift | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Modules/Account/Sources/Account/AccountManager.swift b/Modules/Account/Sources/Account/AccountManager.swift index 6bb69ac50..5ddb750a0 100644 --- a/Modules/Account/Sources/Account/AccountManager.swift +++ b/Modules/Account/Sources/Account/AccountManager.swift @@ -301,10 +301,8 @@ import ActivityLog } public func receiveRemoteNotification(userInfo: [AnyHashable: Any]) async { - Task { - for account in activeAccounts { - await account.receiveRemoteNotification(userInfo: userInfo) - } + for account in activeAccounts { + await account.receiveRemoteNotification(userInfo: userInfo) } } From 7b004a155f80f35614661c8e540e09f9cff5cbbd Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Sat, 5 Sep 2026 09:33:54 -0700 Subject: [PATCH 02/25] =?UTF-8?q?Assume=20network=20is=20reachable=20when?= =?UTF-8?q?=20we=20don=E2=80=99t=20know=20yet.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Modules/RSWeb/Sources/RSWeb/NetworkMonitor.swift | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Modules/RSWeb/Sources/RSWeb/NetworkMonitor.swift b/Modules/RSWeb/Sources/RSWeb/NetworkMonitor.swift index 39798290a..81ce508ff 100644 --- a/Modules/RSWeb/Sources/RSWeb/NetworkMonitor.swift +++ b/Modules/RSWeb/Sources/RSWeb/NetworkMonitor.swift @@ -16,7 +16,7 @@ nonisolated public final class NetworkMonitor: Sendable { private let queue = DispatchQueue(label: "RSWeb NetworkMonitor") private struct State: Sendable { - var isConnected = false + var isConnected: Bool? var connectionType: NWInterface.InterfaceType? var isExpensive = false var isConstrained = false @@ -24,8 +24,10 @@ nonisolated public final class NetworkMonitor: Sendable { private let state = OSAllocatedUnfairLock(initialState: State()) + /// `true` until `NWPathMonitor` delivers its first path, so callers attempt + /// network work rather than skip it on an answer we don't have yet. public var isConnected: Bool { - state.withLock { $0.isConnected } + state.withLock { $0.isConnected ?? true } } public var connectionType: NWInterface.InterfaceType? { From 8b4221eb0a4daa6c999d3bd2ba5d98e3839c6f11 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Sat, 5 Sep 2026 09:36:34 -0700 Subject: [PATCH 03/25] =?UTF-8?q?Drop=20the=20network=20check,=20since=20w?= =?UTF-8?q?e=20don=E2=80=99t=20know=20network=20status=20when=20this=20cod?= =?UTF-8?q?e=20runs=20(it=20runs=20at=20startup).?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Shared/Extensions/CacheCleaner.swift | 34 ++++++++++++---------------- 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/Shared/Extensions/CacheCleaner.swift b/Shared/Extensions/CacheCleaner.swift index aed75196a..a553e040e 100644 --- a/Shared/Extensions/CacheCleaner.swift +++ b/Shared/Extensions/CacheCleaner.swift @@ -9,7 +9,6 @@ import Foundation import RSCore import os -import RSWeb struct CacheCleaner { @@ -26,28 +25,25 @@ struct CacheCleaner { return } - // If the image disk cache hasn't been flushed for 3 days and the network is available, delete it + // If the image disk cache hasn't been flushed for 3 days, delete it if flushDate.addingTimeInterval(3600 * 24 * 3) < Date() { - if NetworkMonitor.shared.isConnected { + let tempDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first! + let faviconsFolderURL = tempDir.appendingPathComponent("Favicons") + let imagesFolderURL = tempDir.appendingPathComponent("Images") + let feedURLToIconURL = tempDir.appendingPathComponent("FeedURLToIconURLCache.plist") + let homePageToIconURL = tempDir.appendingPathComponent("HomePageToIconURLCache.plist") + let homePagesWithNoIconURL = tempDir.appendingPathComponent("HomePagesWithNoIconURLCache.plist") - let tempDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first! - let faviconsFolderURL = tempDir.appendingPathComponent("Favicons") - let imagesFolderURL = tempDir.appendingPathComponent("Images") - let feedURLToIconURL = tempDir.appendingPathComponent("FeedURLToIconURLCache.plist") - let homePageToIconURL = tempDir.appendingPathComponent("HomePageToIconURLCache.plist") - let homePagesWithNoIconURL = tempDir.appendingPathComponent("HomePagesWithNoIconURLCache.plist") - - for tempItem in [faviconsFolderURL, imagesFolderURL, feedURLToIconURL, homePageToIconURL, homePagesWithNoIconURL] { - do { - logger.info("Removing cache file: \(tempItem.absoluteString)") - try FileManager.default.removeItem(at: tempItem) - } catch { - logger.error("Could not delete cache file: \(error.localizedDescription)") - } + for tempItem in [faviconsFolderURL, imagesFolderURL, feedURLToIconURL, homePageToIconURL, homePagesWithNoIconURL] { + do { + logger.info("Removing cache file: \(tempItem.absoluteString)") + try FileManager.default.removeItem(at: tempItem) + } catch { + logger.error("Could not delete cache file: \(error.localizedDescription)") } - - AppDefaults.shared.lastImageCacheFlushDate = Date() } + + AppDefaults.shared.lastImageCacheFlushDate = Date() } } } From 6c66c52a89350eff589b4d72e537576fa363f522 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Sat, 5 Sep 2026 09:41:38 -0700 Subject: [PATCH 04/25] Return true or false from refreshAll so callers can know if the refreshAll ran. --- Modules/Account/Sources/Account/AccountManager.swift | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/Modules/Account/Sources/Account/AccountManager.swift b/Modules/Account/Sources/Account/AccountManager.swift index 5ddb750a0..ffb3d8337 100644 --- a/Modules/Account/Sources/Account/AccountManager.swift +++ b/Modules/Account/Sources/Account/AccountManager.swift @@ -314,10 +314,13 @@ import ActivityLog } } - public func refreshAll(errorHandler: ErrorHandlerCallback? = nil) async { + /// Returns `true` if the refresh ran, `false` if it was skipped + /// due to no network connection. + @discardableResult + public func refreshAll(errorHandler: ErrorHandlerCallback? = nil) async -> Bool { guard NetworkMonitor.shared.isConnected else { Self.logger.info("AccountManager: skipping refreshAll — not connected to internet.") - return + return false } CombinedRefreshProgress.shared.start() @@ -336,6 +339,8 @@ import ActivityLog } } } + + return true } public func sendArticleStatusAll() async { From 819d0c08c0c73f66e58903be1d15aaa7903047ee Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Sat, 5 Sep 2026 10:08:28 -0700 Subject: [PATCH 05/25] =?UTF-8?q?Report=20no=20refresh=20to=20background?= =?UTF-8?q?=20scheduler=20when=20there=E2=80=99s=20no=20network=20connecti?= =?UTF-8?q?on.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- iOS/AppDelegate.swift | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/iOS/AppDelegate.swift b/iOS/AppDelegate.swift index ecc08da7e..f213c3bc9 100644 --- a/iOS/AppDelegate.swift +++ b/iOS/AppDelegate.swift @@ -423,8 +423,14 @@ private extension AppDelegate { let refreshTaskIsCompleted = OSAllocatedUnfairLock(initialState: false) + enum RefreshOutcome { + case completed + case noNetwork + case expired + } + /// Make sure task.setTaskCompleted is called exactly once. - func completeRefreshTask(success: Bool) { + func completeRefreshTask(_ outcome: RefreshOutcome) { let shouldComplete = refreshTaskIsCompleted.withLock { isCompleted -> Bool in if isCompleted { return false @@ -435,11 +441,20 @@ private extension AppDelegate { guard shouldComplete else { return } - if success { + + let success: Bool + switch outcome { + case .completed: Self.logger.info("Background refresh completed.") - } else { + success = true + case .noNetwork: + Self.logger.info("Background refresh skipped — no network path.") + success = false + case .expired: Self.logger.info("Background refresh terminated for running too long.") + success = false } + task.setTaskCompleted(success: success) } @@ -447,17 +462,17 @@ private extension AppDelegate { if AccountManager.shared.isSuspended { AccountManager.shared.resumeAll() } - await AccountManager.shared.refreshAll(errorHandler: ErrorHandler.log) + let didRefresh = await AccountManager.shared.refreshAll(errorHandler: ErrorHandler.log) if !Task.isCancelled { await WidgetDataEncoder.shared?.encodeAndWait() } self.suspendApplication() - completeRefreshTask(success: true) + completeRefreshTask(didRefresh ? .completed : .noNetwork) } task.expirationHandler = { refreshTask.cancel() - completeRefreshTask(success: false) + completeRefreshTask(.expired) Task { @MainActor in self.suspendApplication() } From 0c913d99e39a9784624b3571feb281c804be58f5 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Mon, 7 Sep 2026 09:50:29 -0700 Subject: [PATCH 06/25] Fix bug creating test account folder. --- Modules/Account/Tests/AccountTests/TestAccountManager.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/Account/Tests/AccountTests/TestAccountManager.swift b/Modules/Account/Tests/AccountTests/TestAccountManager.swift index 4cfc362f1..bb8ebeb46 100644 --- a/Modules/Account/Tests/AccountTests/TestAccountManager.swift +++ b/Modules/Account/Tests/AccountTests/TestAccountManager.swift @@ -31,7 +31,7 @@ import RSWeb abort() } - let account = Account(dataFolder: accountFolder.absoluteString, type: type, accountID: accountID) + let account = Account(dataFolder: accountFolder.path, type: type, accountID: accountID) return account } From 6829887c2fb5368ec9251b6e5eddb92220d637bc Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Mon, 7 Sep 2026 09:56:00 -0700 Subject: [PATCH 07/25] Continue sending Feedbin statuses even after one group fails. Add tests. --- .../Feedbin/FeedbinAccountDelegate.swift | 28 +++++++++-- .../Feedbin/FeedbinStatusSendTests.swift | 50 +++++++++++++++++++ 2 files changed, 74 insertions(+), 4 deletions(-) create mode 100644 Modules/Account/Tests/AccountTests/Feedbin/FeedbinStatusSendTests.swift diff --git a/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift b/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift index 3ad33bb40..afa628905 100644 --- a/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift +++ b/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift @@ -119,19 +119,39 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable { } var sentCount = 0 + var savedError: Error? let createUnreadStatuses = Array(syncStatuses.filter { $0.key == SyncStatus.Key.read && $0.flag == false }) - sentCount += try await sendArticleStatuses(createUnreadStatuses, apiCall: caller.createUnreadEntries) + do { + sentCount += try await sendArticleStatuses(createUnreadStatuses, apiCall: caller.createUnreadEntries) + } catch { + savedError = error + } let deleteUnreadStatuses = Array(syncStatuses.filter { $0.key == SyncStatus.Key.read && $0.flag == true }) - sentCount += try await sendArticleStatuses(deleteUnreadStatuses, apiCall: caller.deleteUnreadEntries) + do { + sentCount += try await sendArticleStatuses(deleteUnreadStatuses, apiCall: caller.deleteUnreadEntries) + } catch { + savedError = error + } let createStarredStatuses = Array(syncStatuses.filter { $0.key == SyncStatus.Key.starred && $0.flag == true }) - sentCount += try await sendArticleStatuses(createStarredStatuses, apiCall: caller.createStarredEntries) + do { + sentCount += try await sendArticleStatuses(createStarredStatuses, apiCall: caller.createStarredEntries) + } catch { + savedError = error + } let deleteStarredStatuses = Array(syncStatuses.filter { $0.key == SyncStatus.Key.starred && $0.flag == false }) - sentCount += try await sendArticleStatuses(deleteStarredStatuses, apiCall: caller.deleteStarredEntries) + do { + sentCount += try await sendArticleStatuses(deleteStarredStatuses, apiCall: caller.deleteStarredEntries) + } catch { + savedError = error + } + if let savedError { + throw savedError + } return sentCount } } catch { diff --git a/Modules/Account/Tests/AccountTests/Feedbin/FeedbinStatusSendTests.swift b/Modules/Account/Tests/AccountTests/Feedbin/FeedbinStatusSendTests.swift new file mode 100644 index 000000000..90d3a4621 --- /dev/null +++ b/Modules/Account/Tests/AccountTests/Feedbin/FeedbinStatusSendTests.swift @@ -0,0 +1,50 @@ +// +// FeedbinStatusSendTests.swift +// AccountTests +// +// Created by Brent Simmons on 9/5/26. +// + +import Foundation +import Testing +import RSWeb +import SyncDatabase +@testable import Account + +@MainActor struct FeedbinStatusSendTests { + + /// A permanently-rejected unread status used to abort the remaining groups, + /// so starring and unstarring never reached the server again. + @Test func failingUnreadGroupStillSendsStarredGroup() async throws { + TestingURLProtocol.reset() + defer { + TestingURLProtocol.reset() + } + + // Matching is by URL substring, so both unread calls fail and both starred calls + // fall through to the default 200. + TestingURLProtocol.responses["unread_entries.json"] = TestingURLProtocol.Response(statusCode: 422) + + let account = TestAccountManager.shared.createAccount(type: .feedbin) + defer { + TestAccountManager.shared.deleteAccount(account) + } + + let databasePath = URL(filePath: account.dataFolder).appendingPathComponent("Sync.sqlite3").path + let syncDatabase = SyncDatabase(databasePath: databasePath) + await syncDatabase.insertStatuses([ + SyncStatus(articleID: "1", key: .read, flag: false), + SyncStatus(articleID: "2", key: .starred, flag: true) + ]) + + await #expect(throws: (any Error).self) { + try await account.sendArticleStatus() + } + + let pendingReadArticleIDs = await syncDatabase.selectPendingReadStatusArticleIDs() + #expect(pendingReadArticleIDs == ["1"]) + + let pendingStarredArticleIDs = await syncDatabase.selectPendingStarredStatusArticleIDs() + #expect(pendingStarredArticleIDs == []) + } +} From 181a1744d3a19c8da1baaef3a10920d0749202da Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Mon, 7 Sep 2026 10:25:01 -0700 Subject: [PATCH 08/25] Add lock. --- .../WebServices/TestingURLProtocol.swift | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift b/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift index 2e0aa034a..ab81185b0 100644 --- a/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift +++ b/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift @@ -6,6 +6,7 @@ // import Foundation +import os public final class TestingURLProtocol: URLProtocol { @@ -21,12 +22,23 @@ public final class TestingURLProtocol: URLProtocol { } /// Maps a URL substring to the response to return for matching requests. - /// Populated by tests; consulted per request, so it may change between requests. - nonisolated(unsafe) public static var responses = [String: Response]() + /// Written by tests, read on the URL loading system's thread, so it's behind a lock. + private static let responses = OSAllocatedUnfairLock<[String: Response]>(initialState: [:]) + + /// Register the response to return for requests whose URL contains `urlSubstring`. + public static func setResponse(_ response: Response, forURLContaining urlSubstring: String) { + responses.withLock { $0[urlSubstring] = response } + } /// Clears all registered responses. Call between tests. public static func reset() { - responses = [:] + responses.withLock { $0 = [:] } + } + + private static func response(forURLString urlString: String) -> Response? { + responses.withLock { responses in + responses.first { urlString.contains($0.key) }?.value + } } public override static func canInit(with request: URLRequest) -> Bool { @@ -45,7 +57,7 @@ public final class TestingURLProtocol: URLProtocol { } let urlString = url.absoluteString - let match = Self.responses.first { urlString.contains($0.key) }?.value + let match = Self.response(forURLString: urlString) let httpResponse = HTTPURLResponse(url: url, statusCode: match?.statusCode ?? 200, httpVersion: "HTTP/1.1", headerFields: nil)! client?.urlProtocol(self, didReceive: httpResponse, cacheStoragePolicy: .notAllowed) From 1dff40fa4ac85393c220e29673a336bd591f93f6 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Wed, 9 Sep 2026 08:44:18 -0700 Subject: [PATCH 09/25] Do separate TestingURLProtocol responses per-test. --- .../Feedbin/FeedbinFeedNameTests.swift | 45 +++++----- .../Feedbin/FeedbinStatusSendTests.swift | 67 +++++++-------- .../TestingURLProtocol+Responses.swift | 2 +- .../Tests/AccountTests/WebserviceTests.swift | 18 ++++ .../WebServices/TestingURLProtocol.swift | 42 +++++++--- .../WebServices/URLSession+Webservice.swift | 7 ++ .../TestingURLProtocolIsolationTests.swift | 82 +++++++++++++++++++ 7 files changed, 198 insertions(+), 65 deletions(-) create mode 100644 Modules/Account/Tests/AccountTests/WebserviceTests.swift create mode 100644 Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolIsolationTests.swift diff --git a/Modules/Account/Tests/AccountTests/Feedbin/FeedbinFeedNameTests.swift b/Modules/Account/Tests/AccountTests/Feedbin/FeedbinFeedNameTests.swift index 81180029b..d44a0276f 100644 --- a/Modules/Account/Tests/AccountTests/Feedbin/FeedbinFeedNameTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedbin/FeedbinFeedNameTests.swift @@ -9,31 +9,34 @@ import Testing import RSWeb @testable import Account -@MainActor struct FeedbinFeedNameTests { +extension WebserviceTests { - private static let daringFireballFeedID = "1296379" + @MainActor struct FeedbinFeedNameTests { - private let accountManager = TestAccountManager() + private static let daringFireballFeedID = "1296379" - @Test func refreshLeavesEditedNameAlone() async throws { - TestingURLProtocol.reset() - TestingURLProtocol.setResponse("tags.json", file: "JSON/tags_add.json") - TestingURLProtocol.setResponse("subscriptions.json", file: "JSON/subscriptions_initial.json") + private let accountManager = TestAccountManager() - let account = accountManager.createAccount(type: .feedbin) - defer { - accountManager.deleteAccount(account) + @Test func refreshLeavesEditedNameAlone() async throws { + TestingURLProtocol.reset() + TestingURLProtocol.setResponse("tags.json", file: "JSON/tags_add.json") + TestingURLProtocol.setResponse("subscriptions.json", file: "JSON/subscriptions_initial.json") + + let account = accountManager.createAccount(type: .feedbin) + defer { + accountManager.deleteAccount(account) + } + + try await account.refreshAll() + let feed = try #require(account.idToFeedDictionary[Self.daringFireballFeedID]) + feed.editedName = "Edited Name" + + // A second refresh sees the same server name and must not touch the rename. + try await account.refreshAll() + + #expect(feed.editedName == "Edited Name") + #expect(feed.name == "Daring Fireball") + #expect(feed.nameForDisplay == "Edited Name") } - - try await account.refreshAll() - let feed = try #require(account.idToFeedDictionary[Self.daringFireballFeedID]) - feed.editedName = "Edited Name" - - // A second refresh sees the same server name and must not touch the rename. - try await account.refreshAll() - - #expect(feed.editedName == "Edited Name") - #expect(feed.name == "Daring Fireball") - #expect(feed.nameForDisplay == "Edited Name") } } diff --git a/Modules/Account/Tests/AccountTests/Feedbin/FeedbinStatusSendTests.swift b/Modules/Account/Tests/AccountTests/Feedbin/FeedbinStatusSendTests.swift index 90d3a4621..4a20a8167 100644 --- a/Modules/Account/Tests/AccountTests/Feedbin/FeedbinStatusSendTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedbin/FeedbinStatusSendTests.swift @@ -11,40 +11,43 @@ import RSWeb import SyncDatabase @testable import Account -@MainActor struct FeedbinStatusSendTests { +extension WebserviceTests { - /// A permanently-rejected unread status used to abort the remaining groups, - /// so starring and unstarring never reached the server again. - @Test func failingUnreadGroupStillSendsStarredGroup() async throws { - TestingURLProtocol.reset() - defer { + @MainActor struct FeedbinStatusSendTests { + + /// A permanently-rejected unread status used to abort the remaining groups, + /// so starring and unstarring never reached the server again. + @Test func failingUnreadGroupStillSendsStarredGroup() async throws { TestingURLProtocol.reset() + defer { + TestingURLProtocol.reset() + } + + // Matching is by URL substring, so both unread calls fail and both starred calls + // fall through to the default 200. + TestingURLProtocol.setResponse(.init(statusCode: 422), forURLContaining: "unread_entries.json") + + let account = TestAccountManager.shared.createAccount(type: .feedbin) + defer { + TestAccountManager.shared.deleteAccount(account) + } + + let databasePath = URL(filePath: account.dataFolder).appendingPathComponent("Sync.sqlite3").path + let syncDatabase = SyncDatabase(databasePath: databasePath) + await syncDatabase.insertStatuses([ + SyncStatus(articleID: "1", key: .read, flag: false), + SyncStatus(articleID: "2", key: .starred, flag: true) + ]) + + await #expect(throws: (any Error).self) { + try await account.sendArticleStatus() + } + + let pendingReadArticleIDs = await syncDatabase.selectPendingReadStatusArticleIDs() + #expect(pendingReadArticleIDs == ["1"]) + + let pendingStarredArticleIDs = await syncDatabase.selectPendingStarredStatusArticleIDs() + #expect(pendingStarredArticleIDs == []) } - - // Matching is by URL substring, so both unread calls fail and both starred calls - // fall through to the default 200. - TestingURLProtocol.responses["unread_entries.json"] = TestingURLProtocol.Response(statusCode: 422) - - let account = TestAccountManager.shared.createAccount(type: .feedbin) - defer { - TestAccountManager.shared.deleteAccount(account) - } - - let databasePath = URL(filePath: account.dataFolder).appendingPathComponent("Sync.sqlite3").path - let syncDatabase = SyncDatabase(databasePath: databasePath) - await syncDatabase.insertStatuses([ - SyncStatus(articleID: "1", key: .read, flag: false), - SyncStatus(articleID: "2", key: .starred, flag: true) - ]) - - await #expect(throws: (any Error).self) { - try await account.sendArticleStatus() - } - - let pendingReadArticleIDs = await syncDatabase.selectPendingReadStatusArticleIDs() - #expect(pendingReadArticleIDs == ["1"]) - - let pendingStarredArticleIDs = await syncDatabase.selectPendingStarredStatusArticleIDs() - #expect(pendingStarredArticleIDs == []) } } diff --git a/Modules/Account/Tests/AccountTests/TestingURLProtocol+Responses.swift b/Modules/Account/Tests/AccountTests/TestingURLProtocol+Responses.swift index fad4f9911..6b5cbf91f 100644 --- a/Modules/Account/Tests/AccountTests/TestingURLProtocol+Responses.swift +++ b/Modules/Account/Tests/AccountTests/TestingURLProtocol+Responses.swift @@ -21,6 +21,6 @@ extension TestingURLProtocol { } catch { fatalError("Unable to read response file at \(fileURL) because \(error).") } - responses[urlSubstring] = Response(statusCode: statusCode, data: data) + setResponse(Response(statusCode: statusCode, data: data), forURLContaining: urlSubstring) } } diff --git a/Modules/Account/Tests/AccountTests/WebserviceTests.swift b/Modules/Account/Tests/AccountTests/WebserviceTests.swift new file mode 100644 index 000000000..04872ee53 --- /dev/null +++ b/Modules/Account/Tests/AccountTests/WebserviceTests.swift @@ -0,0 +1,18 @@ +// +// WebserviceTests.swift +// AccountTests +// +// Created by Brent Simmons on 9/7/26. +// + +import Testing + +/// Parent of every suite that registers canned responses with `TestingURLProtocol`. +/// +/// They share one global response table, and Swift Testing runs tests in parallel by default, +/// so one suite's `reset()` can wipe another's registrations while its requests are in flight. +/// `.serialized` applies to nested suites, so nesting here keeps them from interleaving. +/// +/// Any new suite that stubs webservice responses belongs here, whatever the account type. +@Suite(.serialized) struct WebserviceTests { +} diff --git a/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift b/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift index ab81185b0..52f2e07cd 100644 --- a/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift +++ b/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift @@ -21,23 +21,44 @@ public final class TestingURLProtocol: URLProtocol { } } - /// Maps a URL substring to the response to return for matching requests. - /// Written by tests, read on the URL loading system's thread, so it's behind a lock. - private static let responses = OSAllocatedUnfairLock<[String: Response]>(initialState: [:]) + /// Identifies the running test. A session built by `URLSession.makeWebserviceSession()` + /// inside a scope where this is bound carries it, so concurrent tests registering the + /// same URL substring don't see each other's responses. + @TaskLocal public static var currentTestID: String? + + /// Carries `currentTestID` from the session's configuration to `startLoading`. + public static let testIDHeaderField = "X-NetNewsWire-Testing-ID" + + /// Maps a test ID to that test's URL-substring-to-response table. Requests from a session + /// built outside a `currentTestID` scope use `sharedTestID`. + private static let responses = OSAllocatedUnfairLock<[String: [String: Response]]>(initialState: [:]) + + private static let sharedTestID = "shared" /// Register the response to return for requests whose URL contains `urlSubstring`. public static func setResponse(_ response: Response, forURLContaining urlSubstring: String) { - responses.withLock { $0[urlSubstring] = response } + let testID = currentTestID ?? sharedTestID + responses.withLock { $0[testID, default: [:]][urlSubstring] = response } } - /// Clears all registered responses. Call between tests. + /// Clears the responses registered by the current test. Call between tests. public static func reset() { - responses.withLock { $0 = [:] } + removeResponses(forTestID: currentTestID ?? sharedTestID) } - private static func response(forURLString urlString: String) -> Response? { - responses.withLock { responses in - responses.first { urlString.contains($0.key) }?.value + /// Discards one test's responses, for a scope that is ending. + public static func removeResponses(forTestID testID: String) { + responses.withLock { $0[testID] = nil } + } + + private static func response(for request: URLRequest) -> Response? { + guard let urlString = request.url?.absoluteString else { + return nil + } + + let testID = request.value(forHTTPHeaderField: testIDHeaderField) ?? sharedTestID + return responses.withLock { responses in + responses[testID]?.first { urlString.contains($0.key) }?.value } } @@ -56,8 +77,7 @@ public final class TestingURLProtocol: URLProtocol { return } - let urlString = url.absoluteString - let match = Self.response(forURLString: urlString) + let match = Self.response(for: request) let httpResponse = HTTPURLResponse(url: url, statusCode: match?.statusCode ?? 200, httpVersion: "HTTP/1.1", headerFields: nil)! client?.urlProtocol(self, didReceive: httpResponse, cacheStoragePolicy: .notAllowed) diff --git a/Modules/RSWeb/Sources/RSWeb/WebServices/URLSession+Webservice.swift b/Modules/RSWeb/Sources/RSWeb/WebServices/URLSession+Webservice.swift index 5e2738076..85e1bf1ae 100644 --- a/Modules/RSWeb/Sources/RSWeb/WebServices/URLSession+Webservice.swift +++ b/Modules/RSWeb/Sources/RSWeb/WebServices/URLSession+Webservice.swift @@ -58,6 +58,13 @@ nonisolated extension URLSession { if Platform.isRunningUnitTests { sessionConfiguration.protocolClasses = [TestingURLProtocol.self] + + // Stamp the session so the protocol can tell this test's requests from another's. + if let testID = TestingURLProtocol.currentTestID { + var headers = sessionConfiguration.httpAdditionalHeaders ?? [:] + headers[TestingURLProtocol.testIDHeaderField] = testID + sessionConfiguration.httpAdditionalHeaders = headers + } } return URLSession(configuration: sessionConfiguration) diff --git a/Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolIsolationTests.swift b/Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolIsolationTests.swift new file mode 100644 index 000000000..daa5db3d6 --- /dev/null +++ b/Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolIsolationTests.swift @@ -0,0 +1,82 @@ +// +// TestingURLProtocolIsolationTests.swift +// RSWebTests +// +// Created by Brent Simmons on 9/7/26. +// + +import Foundation +import Testing +import RSCore +@testable import RSWeb + +struct TestingURLProtocolIsolationTests { + + private static let url = URL(string: "https://example.com/subscriptions.json")! + private static let urlSubstring = "subscriptions.json" + + @Test func concurrentTestsDoNotSeeEachOthersResponses() async throws { + try #require(Platform.isRunningUnitTests) + + async let first = Self.statusCode(forTestID: "first", registering: 418) + async let second = Self.statusCode(forTestID: "second", registering: 503) + + let (firstStatusCode, secondStatusCode) = try await (first, second) + #expect(firstStatusCode == 418) + #expect(secondStatusCode == 503) + } + + @Test func resetClearsOnlyTheCurrentTestsResponses() async throws { + try #require(Platform.isRunningUnitTests) + + TestingURLProtocol.$currentTestID.withValue("keeper") { + TestingURLProtocol.setResponse(.init(statusCode: 418), forURLContaining: Self.urlSubstring) + } + defer { + TestingURLProtocol.removeResponses(forTestID: "keeper") + } + + TestingURLProtocol.$currentTestID.withValue("resetter") { + TestingURLProtocol.setResponse(.init(statusCode: 503), forURLContaining: Self.urlSubstring) + TestingURLProtocol.reset() + } + + let statusCode = try await TestingURLProtocol.$currentTestID.withValue("keeper") { + try await Self.statusCode(for: Self.url) + } + #expect(statusCode == 418) + } + + @Test func aSessionBuiltOutsideATestScopeUsesTheSharedResponses() async throws { + try #require(Platform.isRunningUnitTests) + + TestingURLProtocol.setResponse(.init(statusCode: 404), forURLContaining: Self.urlSubstring) + defer { + TestingURLProtocol.reset() + } + + let statusCode = try await Self.statusCode(for: Self.url) + #expect(statusCode == 404) + } +} + +private extension TestingURLProtocolIsolationTests { + + /// Registers a response and fetches it, all inside one test-ID scope, so the session + /// created here carries that ID. + static func statusCode(forTestID testID: String, registering statusCode: Int) async throws -> Int { + try await TestingURLProtocol.$currentTestID.withValue(testID) { + defer { + TestingURLProtocol.removeResponses(forTestID: testID) + } + TestingURLProtocol.setResponse(.init(statusCode: statusCode), forURLContaining: urlSubstring) + return try await Self.statusCode(for: url) + } + } + + static func statusCode(for url: URL) async throws -> Int { + let session = URLSession.makeWebserviceSession() + let (_, response) = try await session.data(from: url) + return try #require(response as? HTTPURLResponse).statusCode + } +} From 3a5a6b550890b5f5ee84df089317f8e4dff543b4 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Sun, 13 Sep 2026 10:34:54 -0700 Subject: [PATCH 10/25] Make syncDatabase available to tests. --- .../Sources/Account/Feedbin/FeedbinAccountDelegate.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift b/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift index afa628905..8b7f65712 100644 --- a/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift +++ b/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift @@ -51,7 +51,7 @@ public enum FeedbinAccountDelegateError: String, Error, Sendable { } } - private let syncDatabase: SyncDatabase + let syncDatabase: SyncDatabase private let caller: FeedbinAPICaller private var articlesRefreshedCount = 0 private static let logger = Feedbin.logger From 4b41d7f8a9a6c87a691acfc1f2bedc7df9597d6d Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Sun, 13 Sep 2026 10:36:04 -0700 Subject: [PATCH 11/25] Make each web service test get its own test responses. --- .../Feedbin/FeedbinFeedNameTests.swift | 44 ++++++------- .../Feedbin/FeedbinStatusSendTests.swift | 62 ++++++++----------- .../IsolatedWebserviceResponsesTrait.swift | 40 ++++++++++++ ...solatedWebserviceResponsesTraitTests.swift | 40 ++++++++++++ .../Tests/AccountTests/WebserviceTests.swift | 18 ------ 5 files changed, 126 insertions(+), 78 deletions(-) create mode 100644 Modules/Account/Tests/AccountTests/IsolatedWebserviceResponsesTrait.swift create mode 100644 Modules/Account/Tests/AccountTests/IsolatedWebserviceResponsesTraitTests.swift delete mode 100644 Modules/Account/Tests/AccountTests/WebserviceTests.swift diff --git a/Modules/Account/Tests/AccountTests/Feedbin/FeedbinFeedNameTests.swift b/Modules/Account/Tests/AccountTests/Feedbin/FeedbinFeedNameTests.swift index d44a0276f..4777410cf 100644 --- a/Modules/Account/Tests/AccountTests/Feedbin/FeedbinFeedNameTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedbin/FeedbinFeedNameTests.swift @@ -9,34 +9,30 @@ import Testing import RSWeb @testable import Account -extension WebserviceTests { +@Suite(.isolatedWebserviceResponses) @MainActor struct FeedbinFeedNameTests { - @MainActor struct FeedbinFeedNameTests { + private static let daringFireballFeedID = "1296379" - private static let daringFireballFeedID = "1296379" + private let accountManager = TestAccountManager() - private let accountManager = TestAccountManager() + @Test func refreshLeavesEditedNameAlone() async throws { + TestingURLProtocol.setResponse("tags.json", file: "JSON/tags_add.json") + TestingURLProtocol.setResponse("subscriptions.json", file: "JSON/subscriptions_initial.json") - @Test func refreshLeavesEditedNameAlone() async throws { - TestingURLProtocol.reset() - TestingURLProtocol.setResponse("tags.json", file: "JSON/tags_add.json") - TestingURLProtocol.setResponse("subscriptions.json", file: "JSON/subscriptions_initial.json") - - let account = accountManager.createAccount(type: .feedbin) - defer { - accountManager.deleteAccount(account) - } - - try await account.refreshAll() - let feed = try #require(account.idToFeedDictionary[Self.daringFireballFeedID]) - feed.editedName = "Edited Name" - - // A second refresh sees the same server name and must not touch the rename. - try await account.refreshAll() - - #expect(feed.editedName == "Edited Name") - #expect(feed.name == "Daring Fireball") - #expect(feed.nameForDisplay == "Edited Name") + let account = accountManager.createAccount(type: .feedbin) + defer { + accountManager.deleteAccount(account) } + + try await account.refreshAll() + let feed = try #require(account.idToFeedDictionary[Self.daringFireballFeedID]) + feed.editedName = "Edited Name" + + // A second refresh sees the same server name and must not touch the rename. + try await account.refreshAll() + + #expect(feed.editedName == "Edited Name") + #expect(feed.name == "Daring Fireball") + #expect(feed.nameForDisplay == "Edited Name") } } diff --git a/Modules/Account/Tests/AccountTests/Feedbin/FeedbinStatusSendTests.swift b/Modules/Account/Tests/AccountTests/Feedbin/FeedbinStatusSendTests.swift index 4a20a8167..c753f0f95 100644 --- a/Modules/Account/Tests/AccountTests/Feedbin/FeedbinStatusSendTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedbin/FeedbinStatusSendTests.swift @@ -5,49 +5,39 @@ // Created by Brent Simmons on 9/5/26. // -import Foundation import Testing import RSWeb import SyncDatabase @testable import Account -extension WebserviceTests { +@Suite(.isolatedWebserviceResponses) @MainActor struct FeedbinStatusSendTests { - @MainActor struct FeedbinStatusSendTests { + /// A permanently-rejected unread status used to abort the remaining groups, + /// so starring and unstarring never reached the server again. + @Test func failingUnreadGroupStillSendsStarredGroup() async throws { + // Matching is by URL substring, so both unread calls fail and both starred calls + // fall through to the default 200. + TestingURLProtocol.setResponse(.init(statusCode: 422), forURLContaining: "unread_entries.json") - /// A permanently-rejected unread status used to abort the remaining groups, - /// so starring and unstarring never reached the server again. - @Test func failingUnreadGroupStillSendsStarredGroup() async throws { - TestingURLProtocol.reset() - defer { - TestingURLProtocol.reset() - } - - // Matching is by URL substring, so both unread calls fail and both starred calls - // fall through to the default 200. - TestingURLProtocol.setResponse(.init(statusCode: 422), forURLContaining: "unread_entries.json") - - let account = TestAccountManager.shared.createAccount(type: .feedbin) - defer { - TestAccountManager.shared.deleteAccount(account) - } - - let databasePath = URL(filePath: account.dataFolder).appendingPathComponent("Sync.sqlite3").path - let syncDatabase = SyncDatabase(databasePath: databasePath) - await syncDatabase.insertStatuses([ - SyncStatus(articleID: "1", key: .read, flag: false), - SyncStatus(articleID: "2", key: .starred, flag: true) - ]) - - await #expect(throws: (any Error).self) { - try await account.sendArticleStatus() - } - - let pendingReadArticleIDs = await syncDatabase.selectPendingReadStatusArticleIDs() - #expect(pendingReadArticleIDs == ["1"]) - - let pendingStarredArticleIDs = await syncDatabase.selectPendingStarredStatusArticleIDs() - #expect(pendingStarredArticleIDs == []) + let account = TestAccountManager.shared.createAccount(type: .feedbin) + defer { + TestAccountManager.shared.deleteAccount(account) } + + let syncDatabase = try #require(account.delegate as? FeedbinAccountDelegate).syncDatabase + await syncDatabase.insertStatuses([ + SyncStatus(articleID: "1", key: .read, flag: false), + SyncStatus(articleID: "2", key: .starred, flag: true) + ]) + + await #expect(throws: (any Error).self) { + try await account.sendArticleStatus() + } + + let pendingReadArticleIDs = await syncDatabase.selectPendingReadStatusArticleIDs() + #expect(pendingReadArticleIDs == ["1"]) + + let pendingStarredArticleIDs = await syncDatabase.selectPendingStarredStatusArticleIDs() + #expect(pendingStarredArticleIDs == []) } } diff --git a/Modules/Account/Tests/AccountTests/IsolatedWebserviceResponsesTrait.swift b/Modules/Account/Tests/AccountTests/IsolatedWebserviceResponsesTrait.swift new file mode 100644 index 000000000..ebb69992b --- /dev/null +++ b/Modules/Account/Tests/AccountTests/IsolatedWebserviceResponsesTrait.swift @@ -0,0 +1,40 @@ +// +// IsolatedWebserviceResponsesTrait.swift +// AccountTests +// +// Created by Brent Simmons on 9/9/26. +// + +import Foundation +import Testing +import RSWeb + +/// Gives each test its own `TestingURLProtocol` response table, so suites that stub +/// webservice responses can run in parallel without seeing each other's registrations. +/// +/// Apply it to a suite. It's recursive, so every test in that suite — and in any suite +/// nested inside it — gets a fresh table, and the table is discarded when the test ends. +struct IsolatedWebserviceResponsesTrait: TestTrait, SuiteTrait, TestScoping { + + var isRecursive: Bool { + true + } + + func provideScope(for test: Test, testCase: Test.Case?, performing function: @Sendable () async throws -> Void) async throws { + let testID = UUID().uuidString + try await TestingURLProtocol.$currentTestID.withValue(testID) { + defer { + TestingURLProtocol.removeResponses(forTestID: testID) + } + try await function() + } + } +} + +extension Trait where Self == IsolatedWebserviceResponsesTrait { + + /// Gives each test its own `TestingURLProtocol` response table. + static var isolatedWebserviceResponses: Self { + Self() + } +} diff --git a/Modules/Account/Tests/AccountTests/IsolatedWebserviceResponsesTraitTests.swift b/Modules/Account/Tests/AccountTests/IsolatedWebserviceResponsesTraitTests.swift new file mode 100644 index 000000000..25fe748ca --- /dev/null +++ b/Modules/Account/Tests/AccountTests/IsolatedWebserviceResponsesTraitTests.swift @@ -0,0 +1,40 @@ +// +// IsolatedWebserviceResponsesTraitTests.swift +// AccountTests +// +// Created by Brent Simmons on 9/9/26. +// + +import Foundation +import Testing +import RSWeb + +@Suite(.isolatedWebserviceResponses) struct IsolatedWebserviceResponsesTraitTests { + + private static let url = URL(string: "https://example.com/subscriptions.json")! + + @Test func theTraitBindsATestID() { + #expect(TestingURLProtocol.currentTestID != nil) + } + + @Test func responsesRegisteredHereAreInvisibleUnderAnotherTestID() async throws { + TestingURLProtocol.setResponse(.init(statusCode: 418), forURLContaining: "subscriptions.json") + + let mine = try await Self.statusCode() + #expect(mine == 418) + + let theirs = try await TestingURLProtocol.$currentTestID.withValue("another-test") { + try await Self.statusCode() + } + #expect(theirs == 200) + } +} + +private extension IsolatedWebserviceResponsesTraitTests { + + static func statusCode() async throws -> Int { + let session = URLSession.makeWebserviceSession() + let (_, response) = try await session.data(from: url) + return try #require(response as? HTTPURLResponse).statusCode + } +} diff --git a/Modules/Account/Tests/AccountTests/WebserviceTests.swift b/Modules/Account/Tests/AccountTests/WebserviceTests.swift deleted file mode 100644 index 04872ee53..000000000 --- a/Modules/Account/Tests/AccountTests/WebserviceTests.swift +++ /dev/null @@ -1,18 +0,0 @@ -// -// WebserviceTests.swift -// AccountTests -// -// Created by Brent Simmons on 9/7/26. -// - -import Testing - -/// Parent of every suite that registers canned responses with `TestingURLProtocol`. -/// -/// They share one global response table, and Swift Testing runs tests in parallel by default, -/// so one suite's `reset()` can wipe another's registrations while its requests are in flight. -/// `.serialized` applies to nested suites, so nesting here keeps them from interleaving. -/// -/// Any new suite that stubs webservice responses belongs here, whatever the account type. -@Suite(.serialized) struct WebserviceTests { -} From 68629eca9a3d2b265b0850a89a4316d4efe082f6 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Mon, 14 Sep 2026 09:49:04 -0700 Subject: [PATCH 12/25] =?UTF-8?q?Fetch=20articles=20even=20if=20there?= =?UTF-8?q?=E2=80=99s=20an=20error=20sending=20article=20statuses.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Sources/Account/Feedbin/FeedbinAccountDelegate.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift b/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift index 8b7f65712..2d9bfda13 100644 --- a/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift +++ b/Modules/Account/Sources/Account/Feedbin/FeedbinAccountDelegate.swift @@ -589,7 +589,8 @@ private extension FeedbinAccountDelegate { } func refreshArticlesAndStatuses(_ account: Account) async throws { - try await sendArticleStatus() + // A failed status send must not block fetching new articles. + try? await sendArticleStatus() try await refreshArticleStatus() try await refreshArticles(account) try await refreshMissingArticles(account) From fded0bfab25486362a3b5cbd4a4750eb2d4d01f5 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 15 Sep 2026 10:50:03 -0700 Subject: [PATCH 13/25] Use http method as part of the match for test responses. --- .../TestingURLProtocol+Responses.swift | 4 +- .../WebServices/TestingURLProtocol.swift | 30 +++++-- ...estingURLProtocolMethodMatchingTests.swift | 88 +++++++++++++++++++ 3 files changed, 115 insertions(+), 7 deletions(-) create mode 100644 Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolMethodMatchingTests.swift diff --git a/Modules/Account/Tests/AccountTests/TestingURLProtocol+Responses.swift b/Modules/Account/Tests/AccountTests/TestingURLProtocol+Responses.swift index 6b5cbf91f..6e2780486 100644 --- a/Modules/Account/Tests/AccountTests/TestingURLProtocol+Responses.swift +++ b/Modules/Account/Tests/AccountTests/TestingURLProtocol+Responses.swift @@ -13,7 +13,7 @@ extension TestingURLProtocol { /// Register the response to return for any request whose URL contains `urlSubstring`. /// The body is loaded from `file`, relative to the test bundle resources (e.g. "JSON/tags_add.json"). - static func setResponse(_ urlSubstring: String, file: String, statusCode: Int = 200) { + static func setResponse(_ urlSubstring: String, file: String, statusCode: Int = 200, httpMethod: String? = nil) { let fileURL = Bundle.module.resourceURL!.appendingPathComponent(file) let data: Data do { @@ -21,6 +21,6 @@ extension TestingURLProtocol { } catch { fatalError("Unable to read response file at \(fileURL) because \(error).") } - setResponse(Response(statusCode: statusCode, data: data), forURLContaining: urlSubstring) + setResponse(Response(statusCode: statusCode, data: data), forURLContaining: urlSubstring, httpMethod: httpMethod) } } diff --git a/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift b/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift index 52f2e07cd..38dc0ee72 100644 --- a/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift +++ b/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift @@ -29,16 +29,25 @@ public final class TestingURLProtocol: URLProtocol { /// Carries `currentTestID` from the session's configuration to `startLoading`. public static let testIDHeaderField = "X-NetNewsWire-Testing-ID" - /// Maps a test ID to that test's URL-substring-to-response table. Requests from a session + /// What a registered response answers: a URL substring, and optionally one HTTP method. + private struct ResponseKey: Hashable { + let urlSubstring: String + let httpMethod: String? + } + + /// Maps a test ID to that test's registered responses. Requests from a session /// built outside a `currentTestID` scope use `sharedTestID`. - private static let responses = OSAllocatedUnfairLock<[String: [String: Response]]>(initialState: [:]) + private static let responses = OSAllocatedUnfairLock<[String: [ResponseKey: Response]]>(initialState: [:]) private static let sharedTestID = "shared" /// Register the response to return for requests whose URL contains `urlSubstring`. - public static func setResponse(_ response: Response, forURLContaining urlSubstring: String) { + /// Pass `httpMethod` — `HTTPMethod.post` and friends — to answer only that method. + /// A registration without one answers any method no method-specific registration claims. + public static func setResponse(_ response: Response, forURLContaining urlSubstring: String, httpMethod: String? = nil) { let testID = currentTestID ?? sharedTestID - responses.withLock { $0[testID, default: [:]][urlSubstring] = response } + let key = ResponseKey(urlSubstring: urlSubstring, httpMethod: httpMethod) + responses.withLock { $0[testID, default: [:]][key] = response } } /// Clears the responses registered by the current test. Call between tests. @@ -58,7 +67,18 @@ public final class TestingURLProtocol: URLProtocol { let testID = request.value(forHTTPHeaderField: testIDHeaderField) ?? sharedTestID return responses.withLock { responses in - responses[testID]?.first { urlString.contains($0.key) }?.value + guard let responsesForTest = responses[testID] else { + return nil + } + + func response(forHTTPMethod httpMethod: String?) -> Response? { + responsesForTest.first { key, _ in + key.httpMethod == httpMethod && urlString.contains(key.urlSubstring) + }?.value + } + + // A registration for this request's method wins over one that answers any method. + return response(forHTTPMethod: request.httpMethod) ?? response(forHTTPMethod: nil) } } diff --git a/Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolMethodMatchingTests.swift b/Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolMethodMatchingTests.swift new file mode 100644 index 000000000..fb8820040 --- /dev/null +++ b/Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolMethodMatchingTests.swift @@ -0,0 +1,88 @@ +// +// TestingURLProtocolMethodMatchingTests.swift +// RSWebTests +// +// Created by Brent Simmons on 9/14/26. +// + +import Foundation +import Testing +import RSCore +@testable import RSWeb + +struct TestingURLProtocolMethodMatchingTests { + + private static let url = URL(string: "https://example.com/unread_entries.json")! + private static let urlSubstring = "unread_entries.json" + + @Test func aMethodSpecificResponseAnswersOnlyThatMethod() async throws { + try #require(Platform.isRunningUnitTests) + + try await Self.withItsOwnResponses { + TestingURLProtocol.setResponse(.init(statusCode: 422), forURLContaining: Self.urlSubstring, httpMethod: HTTPMethod.post) + + let postStatusCode = try await Self.statusCode(httpMethod: HTTPMethod.post) + #expect(postStatusCode == 422) + + let getStatusCode = try await Self.statusCode(httpMethod: HTTPMethod.get) + #expect(getStatusCode == 200) + } + } + + @Test func aResponseWithNoMethodAnswersEveryMethod() async throws { + try #require(Platform.isRunningUnitTests) + + try await Self.withItsOwnResponses { + TestingURLProtocol.setResponse(.init(statusCode: 404), forURLContaining: Self.urlSubstring) + + let postStatusCode = try await Self.statusCode(httpMethod: HTTPMethod.post) + #expect(postStatusCode == 404) + + let getStatusCode = try await Self.statusCode(httpMethod: HTTPMethod.get) + #expect(getStatusCode == 404) + + let deleteStatusCode = try await Self.statusCode(httpMethod: HTTPMethod.delete) + #expect(deleteStatusCode == 404) + } + } + + @Test func aMethodSpecificResponseWinsOverOneWithNoMethod() async throws { + try #require(Platform.isRunningUnitTests) + + try await Self.withItsOwnResponses { + TestingURLProtocol.setResponse(.init(statusCode: 404), forURLContaining: Self.urlSubstring) + TestingURLProtocol.setResponse(.init(statusCode: 422), forURLContaining: Self.urlSubstring, httpMethod: HTTPMethod.post) + + let postStatusCode = try await Self.statusCode(httpMethod: HTTPMethod.post) + #expect(postStatusCode == 422) + + let getStatusCode = try await Self.statusCode(httpMethod: HTTPMethod.get) + #expect(getStatusCode == 404) + } + } +} + +private extension TestingURLProtocolMethodMatchingTests { + + /// Runs `body` against its own response table. RSWebTests has no trait to do this + /// (`IsolatedWebserviceResponsesTrait` lives in AccountTests), so it's done by hand — + /// without it these tests share one table and clear each other's registrations. + static func withItsOwnResponses(_ body: () async throws -> Void) async throws { + let testID = UUID().uuidString + try await TestingURLProtocol.$currentTestID.withValue(testID) { + defer { + TestingURLProtocol.removeResponses(forTestID: testID) + } + try await body() + } + } + + static func statusCode(httpMethod: String) async throws -> Int { + var request = URLRequest(url: url) + request.httpMethod = httpMethod + + let session = URLSession.makeWebserviceSession() + let (_, response) = try await session.data(for: request) + return try #require(response as? HTTPURLResponse).statusCode + } +} From 177f6ae143337940520a8edc2b1e3fcdd649c588 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 15 Sep 2026 10:50:40 -0700 Subject: [PATCH 14/25] Make sure a failed Feedbin status send still allows article refreshing. --- .../Feedbin/FeedbinStatusSendTests.swift | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/Modules/Account/Tests/AccountTests/Feedbin/FeedbinStatusSendTests.swift b/Modules/Account/Tests/AccountTests/Feedbin/FeedbinStatusSendTests.swift index c753f0f95..0ab3b9eaf 100644 --- a/Modules/Account/Tests/AccountTests/Feedbin/FeedbinStatusSendTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedbin/FeedbinStatusSendTests.swift @@ -40,4 +40,31 @@ import SyncDatabase let pendingStarredArticleIDs = await syncDatabase.selectPendingStarredStatusArticleIDs() #expect(pendingStarredArticleIDs == []) } + + /// A failing status send used to abort the whole refresh, so an account stopped + /// receiving new articles for as long as the send kept failing. + @Test func failingStatusSendDoesNotBlockArticleRefresh() async throws { + TestingURLProtocol.setResponse("tags.json", file: "JSON/tags_add.json") + TestingURLProtocol.setResponse("subscriptions.json", file: "JSON/subscriptions_initial.json") + + // Only the send fails. The status refresh GETs this same path and must still succeed, + // which is why this registration names a method. + TestingURLProtocol.setResponse(.init(statusCode: 422), forURLContaining: "unread_entries.json", httpMethod: HTTPMethod.post) + + let account = TestAccountManager.shared.createAccount(type: .feedbin) + defer { + TestAccountManager.shared.deleteAccount(account) + } + + let syncDatabase = try #require(account.delegate as? FeedbinAccountDelegate).syncDatabase + await syncDatabase.insertStatuses([SyncStatus(articleID: "1", key: .read, flag: false)]) + + try await account.refreshAll() + + // The send really did fail, so its row is still queued. + let pendingReadArticleIDs = await syncDatabase.selectPendingReadStatusArticleIDs() + #expect(pendingReadArticleIDs == ["1"]) + + #expect(account.flattenedFeeds().count == 224) + } } From 3c2c52bb1767fe818b7a946f8268f427c650e536 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 15 Sep 2026 14:55:54 -0700 Subject: [PATCH 15/25] =?UTF-8?q?Send=20statuses=20before=20sending=20arti?= =?UTF-8?q?cle=20content,=20so=20an=20article=20content=20failure=20won?= =?UTF-8?q?=E2=80=99t=20affect=20status=20syncing.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CloudKit/CloudKitArticlesZone.swift | 30 ++++++++++++++----- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZone.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZone.swift index c7aaef9bc..0e6d7d719 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZone.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitArticlesZone.swift @@ -182,7 +182,8 @@ final class CloudKitArticlesZone: CloudKitZone { return 0 } - var modifyRecords = [CKRecord]() + var statusRecords = [CKRecord]() + var articleRecords = [CKRecord]() var newRecords = [CKRecord]() var deleteRecordIDs = [CKRecord.ID]() var contentUploadCount = 0 @@ -193,9 +194,8 @@ final class CloudKitArticlesZone: CloudKitZone { for statusUpdate in statusUpdates { switch statusUpdate.record { case .all: - modifyRecords.append(self.makeStatusRecord(statusUpdate)) - modifyRecords.append(self.makeArticleRecord(statusUpdate.article!)) - contentUploadCount += 1 + statusRecords.append(self.makeStatusRecord(statusUpdate)) + articleRecords.append(self.makeArticleRecord(statusUpdate.article!)) case .new: newRecords.append(self.makeStatusRecord(statusUpdate)) if statusUpdate.article!.status.starred || syncUnreadContent { @@ -207,22 +207,38 @@ final class CloudKitArticlesZone: CloudKitZone { case .delete: deleteRecordIDs.append(CKRecord.ID(recordName: self.statusID(statusUpdate.articleID), zoneID: zoneID)) case .statusOnly: - modifyRecords.append(self.makeStatusRecord(statusUpdate)) + statusRecords.append(self.makeStatusRecord(statusUpdate)) deleteRecordIDs.append(CKRecord.ID(recordName: self.articleID(statusUpdate.articleID), zoneID: zoneID)) } } await Task.detached(priority: .userInitiated) { - self.compressArticleRecords(modifyRecords) + self.compressArticleRecords(articleRecords) self.compressArticleRecords(newRecords) }.value + // Statuses go first, and on their own. They're what sync correctness depends on, and + // `modify` is atomic, so batching them with content records means one article too big + // to store rejects every status in the request. Sending them first is also the right + // order: an article record references its status record. do { - try await modify(recordsToSave: modifyRecords, recordIDsToDelete: deleteRecordIDs) + try await modify(recordsToSave: statusRecords, recordIDsToDelete: deleteRecordIDs) try await saveIfNew(newRecords) } catch { try await handleModifyArticlesError(error, statusUpdates: statusUpdates) + return contentUploadCount } + + // Content is an optimization, so a failure here leaves the statuses sent. + if !articleRecords.isEmpty { + do { + try await modify(recordsToSave: articleRecords, recordIDsToDelete: []) + contentUploadCount += articleRecords.count + } catch { + Self.logger.error("CloudKitArticlesZone: modifyArticles content upload failed: \(error.localizedDescription)") + } + } + return contentUploadCount } From 1e6b8924c23e2d57360876341dedec7024d93a09 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 15 Sep 2026 15:12:31 -0700 Subject: [PATCH 16/25] Distinguish between failure and an empty queue. --- .../CloudKit/CloudKitAccountDelegate.swift | 17 ++++++++++------- .../CloudKit/CloudKitSendStatusOperation.swift | 4 ++++ 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift index e0f1b8e5d..17d447388 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift @@ -188,12 +188,15 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { return false } - let sentCount = try await sendArticleStatus(account: account, showProgress: false) + let sendResult = try await sendArticleStatus(account: account, showProgress: false) try await refreshArticleStatus() let didReceiveChanges = !(articlesZoneHasNoChanges && accountZoneHasNoChanges) - let didWork = sentCount > 0 || didReceiveChanges - if didWork { + let didWork = sendResult.sentCount > 0 || didReceiveChanges + + // A failed send means statuses are still waiting to go out, so this isn't a quiet + // period. Backing off here would also skip receiving for the next half hour. + if didWork || sendResult.didFail { lastNoChangeSyncDate = nil } else { lastNoChangeSyncDate = Date() @@ -1130,10 +1133,10 @@ private extension CloudKitAccountDelegate { Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public) did complete") } - /// Returns the number of statuses successfully sent. - func sendArticleStatus(account: Account, showProgress: Bool) async throws -> Int { + /// Returns the number of statuses successfully sent, and whether any failed to send. + func sendArticleStatus(account: Account, showProgress: Bool) async throws -> (sentCount: Int, didFail: Bool) { Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") - return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<(sentCount: Int, didFail: Bool), Error>) in let op = CloudKitSendStatusOperation(account: account, articlesZone: articlesZone, database: syncDatabase, @@ -1144,7 +1147,7 @@ private extension CloudKitAccountDelegate { if mainThreadOperation.isCanceled { continuation.resume(throwing: CloudKitAccountDelegateError.unknown) } else { - continuation.resume(returning: op.sentCount) + continuation.resume(returning: (op.sentCount, op.didFail)) } } mainThreadOperationQueue.add(op) diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitSendStatusOperation.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitSendStatusOperation.swift index 42bdca8ce..e4a0371a4 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitSendStatusOperation.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitSendStatusOperation.swift @@ -29,6 +29,9 @@ final class CloudKitSendStatusOperation: MainThreadOperation, @unchecked Sendabl /// operation completes. private(set) var sentCount = 0 + /// Whether any statuses failed to send. Read after the operation completes. + private(set) var didFail = false + init(account: Account, articlesZone: CloudKitArticlesZone, database: SyncDatabase, syncArticleContentForUnreadArticles: @escaping @Sendable () -> Bool, syncErrorHandler: CloudKitSyncErrorHandler?) { self.account = account self.accountID = account.accountID @@ -64,6 +67,7 @@ final class CloudKitSendStatusOperation: MainThreadOperation, @unchecked Sendabl activityLog.didComplete(id: activityID, message: message) } } catch { + self.didFail = true Self.logger.debug("iCloud: Send status error: \(error.localizedDescription)") activityLog.didFail(id: activityID, error: error) } From 40227e312c26fd1d0c632a99fb575070bde167be Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 15 Sep 2026 17:36:16 -0700 Subject: [PATCH 17/25] Use url.absoluteString consistently in urlToFeedDictionary so that lookups work as expected. --- .../Account/LocalAccount/LocalAccountRefresher.swift | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/Modules/Account/Sources/Account/LocalAccount/LocalAccountRefresher.swift b/Modules/Account/Sources/Account/LocalAccount/LocalAccountRefresher.swift index f5268a093..48b2038c5 100644 --- a/Modules/Account/Sources/Account/LocalAccount/LocalAccountRefresher.swift +++ b/Modules/Account/Sources/Account/LocalAccount/LocalAccountRefresher.swift @@ -136,20 +136,24 @@ import os return } + // Key on the request URL: `URL(string:)` doesn’t always round-trip feed.url. urlToFeedDictionary.removeAll() + var urls = Set() for feed in filteredFeeds { - urlToFeedDictionary[feed.url] = feed + guard let url = Self.url(for: feed) else { + continue + } + urlToFeedDictionary[url.absoluteString] = feed + urls.insert(url) } - let urls = filteredFeeds.compactMap { Self.url(for: $0) } - // This refresh replaces any in-flight one, so resume its caller rather than stranding it. if let previousCompletion = self.completion { previousCompletion() } self.completion = completion - downloadSession.download(Set(urls)) + downloadSession.download(urls) } private var activityOwner: ActivityOwner? { From d3da14e5b89214d0386934012f290dd2c8c2cf90 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Wed, 16 Sep 2026 09:01:24 -0700 Subject: [PATCH 18/25] Stop reauthorizing a Feedly token that was rejected. --- .../Sources/Account/Feedly/FeedlyAccountDelegate.swift | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift b/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift index 5f917f7ef..610f551dc 100644 --- a/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift +++ b/Modules/Account/Sources/Account/Feedly/FeedlyAccountDelegate.swift @@ -57,6 +57,8 @@ import Secrets var credentials: Credentials? { didSet { + reauthorizationDidFailDefinitively = false + #if DEBUG // https://developer.feedly.com/v3/developer/ if let devToken = ProcessInfo.processInfo.environment["FEEDLY_DEV_ACCESS_TOKEN"], !devToken.isEmpty { @@ -106,6 +108,9 @@ import Secrets // endpoint read as abuse to Feedly and earn the 403 ban. private var reauthorizeTask: Task? + // A rejected refresh token is rejected on the next 401 too. + private var reauthorizationDidFailDefinitively = false + // The refresh timer, background refresh, and the Refresh command can all fire // refreshAll — overlapping runs double the request volume and corrupt progress. private var refreshAllIsRunning = false @@ -1227,6 +1232,9 @@ extension FeedlyAccountDelegate: FeedlyAPICallerDelegate { /// Storing credentials updates `self.credentials` via `Account.storeCredentials`, which in turn /// hands the fresh access token to the caller. func reauthorizeFeedlyAPICaller() async -> Bool { + guard !reauthorizationDidFailDefinitively else { + return false + } if let reauthorizeTask { return await reauthorizeTask.value } @@ -1272,6 +1280,7 @@ extension FeedlyAccountDelegate: FeedlyAPICallerDelegate { } catch { Self.logger.error("Feedly: Refresh access token failed: \(error.localizedDescription)") if isDefinitiveReauthorizationError(error) { + reauthorizationDidFailDefinitively = true account.postSyncError(error, operation: "Refreshing access token") } return false From a76f59c3898eb5606a53028b1979bad70c7827e4 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Wed, 16 Sep 2026 09:16:44 -0700 Subject: [PATCH 19/25] Remove test account credentials from Keychain when deleting account. --- Modules/Account/Tests/AccountTests/TestAccountManager.swift | 6 ++++++ Modules/Secrets/Sources/Secrets/Credentials.swift | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/Modules/Account/Tests/AccountTests/TestAccountManager.swift b/Modules/Account/Tests/AccountTests/TestAccountManager.swift index bb8ebeb46..9cc1c13bd 100644 --- a/Modules/Account/Tests/AccountTests/TestAccountManager.swift +++ b/Modules/Account/Tests/AccountTests/TestAccountManager.swift @@ -8,6 +8,7 @@ import Foundation import RSWeb +import Secrets @testable import Account @@ -38,6 +39,11 @@ import RSWeb func deleteAccount(_ account: Account) { + // Credentials live in the keychain, outside the account folder removed below. + for credentialsType in CredentialsType.allCases { + try? account.removeCredentials(type: credentialsType) + } + account.deleteSettings() do { diff --git a/Modules/Secrets/Sources/Secrets/Credentials.swift b/Modules/Secrets/Sources/Secrets/Credentials.swift index 47c3002a7..96b32d4f6 100644 --- a/Modules/Secrets/Sources/Secrets/Credentials.swift +++ b/Modules/Secrets/Sources/Secrets/Credentials.swift @@ -52,7 +52,7 @@ extension CredentialsError: LocalizedError { } } -public enum CredentialsType: String, Sendable { +public enum CredentialsType: String, CaseIterable, Sendable { case basic = "password" case newsBlurBasic = "newsBlurBasic" case newsBlurSessionID = "newsBlurSessionId" From 9d65e6c8224f97157729c7cfe699394cda8b1390 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Wed, 16 Sep 2026 09:17:42 -0700 Subject: [PATCH 20/25] Make sure a rejected Feedly token is retried just once. --- .../Feedly/FeedlyReauthorizationTests.swift | 58 +++++++++++ .../IsolatedWebserviceResponsesTrait.swift | 2 +- .../WebServices/TestingURLProtocol.swift | 65 +++++++++--- .../TestingURLProtocolIsolationTests.swift | 4 +- ...estingURLProtocolMethodMatchingTests.swift | 2 +- .../TestingURLProtocolRequestCountTests.swift | 99 +++++++++++++++++++ 6 files changed, 215 insertions(+), 15 deletions(-) create mode 100644 Modules/Account/Tests/AccountTests/Feedly/FeedlyReauthorizationTests.swift create mode 100644 Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolRequestCountTests.swift diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlyReauthorizationTests.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlyReauthorizationTests.swift new file mode 100644 index 000000000..d1e8bae6a --- /dev/null +++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlyReauthorizationTests.swift @@ -0,0 +1,58 @@ +// +// FeedlyReauthorizationTests.swift +// AccountTests +// +// Created by Brent Simmons on 9/16/26. +// + +import Testing +import RSWeb +import Secrets +@testable import Account + +@Suite(.isolatedWebserviceResponses) @MainActor struct FeedlyReauthorizationTests { + + private static let tokenEndpoint = "/v3/auth/token" + + /// Every 401 in a refresh cycle used to spawn its own token POST, which is the + /// abuse pattern that earns a 403 ban from Feedly. + @Test func aRejectedRefreshTokenIsOnlyTriedOnce() async throws { + TestingURLProtocol.setResponse(.init(statusCode: 400), forURLContaining: Self.tokenEndpoint, httpMethod: HTTPMethod.post) + + let account = TestAccountManager.shared.createAccount(type: .feedly) + defer { + TestAccountManager.shared.deleteAccount(account) + } + let delegate = try #require(account.delegate as? FeedlyAccountDelegate) + try account.storeCredentials(Credentials(type: .oauthRefreshToken, username: "someone", secret: "rejected-token")) + + let firstResult = await delegate.reauthorizeFeedlyAPICaller() + #expect(firstResult == false) + #expect(TestingURLProtocol.requestCount(forURLContaining: Self.tokenEndpoint) == 1) + + let secondResult = await delegate.reauthorizeFeedlyAPICaller() + #expect(secondResult == false) + #expect(TestingURLProtocol.requestCount(forURLContaining: Self.tokenEndpoint) == 1) + } + + /// The account has to recover when the user signs in again, rather than staying + /// dead until relaunch. + @Test func newCredentialsAllowAnotherAttempt() async throws { + TestingURLProtocol.setResponse(.init(statusCode: 400), forURLContaining: Self.tokenEndpoint, httpMethod: HTTPMethod.post) + + let account = TestAccountManager.shared.createAccount(type: .feedly) + defer { + TestAccountManager.shared.deleteAccount(account) + } + let delegate = try #require(account.delegate as? FeedlyAccountDelegate) + try account.storeCredentials(Credentials(type: .oauthRefreshToken, username: "someone", secret: "rejected-token")) + + _ = await delegate.reauthorizeFeedlyAPICaller() + #expect(TestingURLProtocol.requestCount(forURLContaining: Self.tokenEndpoint) == 1) + + try account.storeCredentials(Credentials(type: .oauthAccessToken, username: "someone", secret: "fresh-token")) + + _ = await delegate.reauthorizeFeedlyAPICaller() + #expect(TestingURLProtocol.requestCount(forURLContaining: Self.tokenEndpoint) == 2) + } +} diff --git a/Modules/Account/Tests/AccountTests/IsolatedWebserviceResponsesTrait.swift b/Modules/Account/Tests/AccountTests/IsolatedWebserviceResponsesTrait.swift index ebb69992b..9f9954bb5 100644 --- a/Modules/Account/Tests/AccountTests/IsolatedWebserviceResponsesTrait.swift +++ b/Modules/Account/Tests/AccountTests/IsolatedWebserviceResponsesTrait.swift @@ -24,7 +24,7 @@ struct IsolatedWebserviceResponsesTrait: TestTrait, SuiteTrait, TestScoping { let testID = UUID().uuidString try await TestingURLProtocol.$currentTestID.withValue(testID) { defer { - TestingURLProtocol.removeResponses(forTestID: testID) + TestingURLProtocol.endTest(withID: testID) } try await function() } diff --git a/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift b/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift index 38dc0ee72..0a02e8c53 100644 --- a/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift +++ b/Modules/RSWeb/Sources/RSWeb/WebServices/TestingURLProtocol.swift @@ -35,9 +35,21 @@ public final class TestingURLProtocol: URLProtocol { let httpMethod: String? } - /// Maps a test ID to that test's registered responses. Requests from a session - /// built outside a `currentTestID` scope use `sharedTestID`. - private static let responses = OSAllocatedUnfairLock<[String: [ResponseKey: Response]]>(initialState: [:]) + /// A request the protocol answered. + private struct AnsweredRequest: Sendable { + let urlString: String + let httpMethod: String? + } + + /// What one test registered, and what it has been asked for since. + private struct TestState: Sendable { + var responses = [ResponseKey: Response]() + var answeredRequests = [AnsweredRequest]() + } + + /// Maps a test ID to its state. Requests from a session built outside a + /// `currentTestID` scope use `sharedTestID`. + private static let testStates = OSAllocatedUnfairLock<[String: TestState]>(initialState: [:]) private static let sharedTestID = "shared" @@ -47,17 +59,46 @@ public final class TestingURLProtocol: URLProtocol { public static func setResponse(_ response: Response, forURLContaining urlSubstring: String, httpMethod: String? = nil) { let testID = currentTestID ?? sharedTestID let key = ResponseKey(urlSubstring: urlSubstring, httpMethod: httpMethod) - responses.withLock { $0[testID, default: [:]][key] = response } + testStates.withLock { $0[testID, default: TestState()].responses[key] = response } } - /// Clears the responses registered by the current test. Call between tests. + /// How many requests this test has been asked for whose URL contains `urlSubstring`. + /// Pass `httpMethod` to count only that method. Counts requests whether or not a + /// response was registered for them. + public static func requestCount(forURLContaining urlSubstring: String, httpMethod: String? = nil) -> Int { + let testID = currentTestID ?? sharedTestID + return testStates.withLock { testStates in + let answeredRequests = testStates[testID]?.answeredRequests ?? [] + return answeredRequests.count { answeredRequest in + guard answeredRequest.urlString.contains(urlSubstring) else { + return false + } + guard let httpMethod else { + return true + } + return answeredRequest.httpMethod == httpMethod + } + } + } + + /// Clears everything recorded for the current test. Call between tests. public static func reset() { - removeResponses(forTestID: currentTestID ?? sharedTestID) + endTest(withID: currentTestID ?? sharedTestID) } - /// Discards one test's responses, for a scope that is ending. - public static func removeResponses(forTestID testID: String) { - responses.withLock { $0[testID] = nil } + /// Discards one test's registrations and request history, for a scope that is ending. + public static func endTest(withID testID: String) { + testStates.withLock { $0[testID] = nil } + } + + private static func recordRequest(_ request: URLRequest) { + guard let urlString = request.url?.absoluteString else { + return + } + + let testID = request.value(forHTTPHeaderField: testIDHeaderField) ?? sharedTestID + let answeredRequest = AnsweredRequest(urlString: urlString, httpMethod: request.httpMethod) + testStates.withLock { $0[testID, default: TestState()].answeredRequests.append(answeredRequest) } } private static func response(for request: URLRequest) -> Response? { @@ -66,8 +107,8 @@ public final class TestingURLProtocol: URLProtocol { } let testID = request.value(forHTTPHeaderField: testIDHeaderField) ?? sharedTestID - return responses.withLock { responses in - guard let responsesForTest = responses[testID] else { + return testStates.withLock { testStates in + guard let responsesForTest = testStates[testID]?.responses else { return nil } @@ -97,6 +138,8 @@ public final class TestingURLProtocol: URLProtocol { return } + Self.recordRequest(request) + let match = Self.response(for: request) let httpResponse = HTTPURLResponse(url: url, statusCode: match?.statusCode ?? 200, httpVersion: "HTTP/1.1", headerFields: nil)! diff --git a/Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolIsolationTests.swift b/Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolIsolationTests.swift index daa5db3d6..530bb39fa 100644 --- a/Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolIsolationTests.swift +++ b/Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolIsolationTests.swift @@ -33,7 +33,7 @@ struct TestingURLProtocolIsolationTests { TestingURLProtocol.setResponse(.init(statusCode: 418), forURLContaining: Self.urlSubstring) } defer { - TestingURLProtocol.removeResponses(forTestID: "keeper") + TestingURLProtocol.endTest(withID: "keeper") } TestingURLProtocol.$currentTestID.withValue("resetter") { @@ -67,7 +67,7 @@ private extension TestingURLProtocolIsolationTests { static func statusCode(forTestID testID: String, registering statusCode: Int) async throws -> Int { try await TestingURLProtocol.$currentTestID.withValue(testID) { defer { - TestingURLProtocol.removeResponses(forTestID: testID) + TestingURLProtocol.endTest(withID: testID) } TestingURLProtocol.setResponse(.init(statusCode: statusCode), forURLContaining: urlSubstring) return try await Self.statusCode(for: url) diff --git a/Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolMethodMatchingTests.swift b/Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolMethodMatchingTests.swift index fb8820040..97fbfd6c7 100644 --- a/Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolMethodMatchingTests.swift +++ b/Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolMethodMatchingTests.swift @@ -71,7 +71,7 @@ private extension TestingURLProtocolMethodMatchingTests { let testID = UUID().uuidString try await TestingURLProtocol.$currentTestID.withValue(testID) { defer { - TestingURLProtocol.removeResponses(forTestID: testID) + TestingURLProtocol.endTest(withID: testID) } try await body() } diff --git a/Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolRequestCountTests.swift b/Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolRequestCountTests.swift new file mode 100644 index 000000000..772509d5d --- /dev/null +++ b/Modules/RSWeb/Tests/RSWebTests/TestingURLProtocolRequestCountTests.swift @@ -0,0 +1,99 @@ +// +// TestingURLProtocolRequestCountTests.swift +// RSWebTests +// +// Created by Brent Simmons on 9/16/26. +// + +import Foundation +import Testing +import RSCore +@testable import RSWeb + +struct TestingURLProtocolRequestCountTests { + + private static let url = URL(string: "https://example.com/v3/auth/token")! + private static let urlSubstring = "/v3/auth/token" + + @Test func requestsAreCounted() async throws { + try #require(Platform.isRunningUnitTests) + + try await Self.withItsOwnResponses { + TestingURLProtocol.setResponse(.init(statusCode: 400), forURLContaining: Self.urlSubstring) + + #expect(TestingURLProtocol.requestCount(forURLContaining: Self.urlSubstring) == 0) + + try await Self.send(httpMethod: HTTPMethod.post) + #expect(TestingURLProtocol.requestCount(forURLContaining: Self.urlSubstring) == 1) + + try await Self.send(httpMethod: HTTPMethod.post) + #expect(TestingURLProtocol.requestCount(forURLContaining: Self.urlSubstring) == 2) + } + } + + @Test func countingCanBeNarrowedToOneMethod() async throws { + try #require(Platform.isRunningUnitTests) + + try await Self.withItsOwnResponses { + try await Self.send(httpMethod: HTTPMethod.post) + try await Self.send(httpMethod: HTTPMethod.get) + + #expect(TestingURLProtocol.requestCount(forURLContaining: Self.urlSubstring, httpMethod: HTTPMethod.post) == 1) + #expect(TestingURLProtocol.requestCount(forURLContaining: Self.urlSubstring, httpMethod: HTTPMethod.get) == 1) + #expect(TestingURLProtocol.requestCount(forURLContaining: Self.urlSubstring) == 2) + } + } + + /// A request with no registered response still counts, so a test can assert that a + /// call it never stubbed was made — or wasn't. + @Test func unstubbedRequestsAreCountedToo() async throws { + try #require(Platform.isRunningUnitTests) + + try await Self.withItsOwnResponses { + try await Self.send(httpMethod: HTTPMethod.get) + + #expect(TestingURLProtocol.requestCount(forURLContaining: Self.urlSubstring) == 1) + #expect(TestingURLProtocol.requestCount(forURLContaining: "/v3/never/called") == 0) + } + } + + @Test func anotherTestsRequestsAreNotCounted() async throws { + try #require(Platform.isRunningUnitTests) + + try await Self.withItsOwnResponses { + try await Self.send(httpMethod: HTTPMethod.post) + + let countInAnotherTest = try await TestingURLProtocol.$currentTestID.withValue("another-test") { + try await Self.send(httpMethod: HTTPMethod.post) + return TestingURLProtocol.requestCount(forURLContaining: Self.urlSubstring) + } + TestingURLProtocol.endTest(withID: "another-test") + + #expect(countInAnotherTest == 1) + #expect(TestingURLProtocol.requestCount(forURLContaining: Self.urlSubstring) == 1) + } + } +} + +private extension TestingURLProtocolRequestCountTests { + + /// Runs `body` against its own response table. RSWebTests has no trait to do this + /// (`IsolatedWebserviceResponsesTrait` lives in AccountTests), so it's done by hand. + static func withItsOwnResponses(_ body: () async throws -> Void) async throws { + let testID = UUID().uuidString + try await TestingURLProtocol.$currentTestID.withValue(testID) { + defer { + TestingURLProtocol.endTest(withID: testID) + } + try await body() + } + } + + static func send(httpMethod: String) async throws { + var request = URLRequest(url: url) + request.httpMethod = httpMethod + + let session = URLSession.makeWebserviceSession() + _ = try await session.data(for: request) + } +} From 602adc798b6a6d3e5a0f0269a3bf7b3086cbfe02 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Wed, 16 Sep 2026 09:48:11 -0700 Subject: [PATCH 21/25] =?UTF-8?q?Register=20for=20silent=20pushes=20on=20M?= =?UTF-8?q?ac=20regardless=20of=20authorization,=20since=20they=20don?= =?UTF-8?q?=E2=80=99t=20need=20it.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Mac/AppDelegate.swift | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/Mac/AppDelegate.swift b/Mac/AppDelegate.swift index 63d47b489..35dfa0546 100644 --- a/Mac/AppDelegate.swift +++ b/Mac/AppDelegate.swift @@ -257,15 +257,8 @@ let appName = "NetNewsWire" refreshTimer = AccountRefreshTimer() ArticleStatusSyncTimer.shared.start() - UNUserNotificationCenter.current().requestAuthorization(options: [.badge]) { _, _ in } - - UNUserNotificationCenter.current().getNotificationSettings { (settings) in - if settings.authorizationStatus == .authorized { - DispatchQueue.main.async { - NSApplication.shared.registerForRemoteNotifications() - } - } - } + // Silent CloudKit pushes don’t need notification permission. + NSApplication.shared.registerForRemoteNotifications() UNUserNotificationCenter.current().delegate = self UserNotificationManager.shared.start() From 7fab15e95379fa617409a40f291088c88b396a51 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Wed, 16 Sep 2026 09:50:15 -0700 Subject: [PATCH 22/25] =?UTF-8?q?Register=20for=20remote=20notifications?= =?UTF-8?q?=20regardless=20of=20other=20authorization=20(silent=20pushes?= =?UTF-8?q?=20don=E2=80=99t=20need=20authorization).?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- iOS/AppDelegate.swift | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/iOS/AppDelegate.swift b/iOS/AppDelegate.swift index f213c3bc9..6268b1368 100644 --- a/iOS/AppDelegate.swift +++ b/iOS/AppDelegate.swift @@ -87,13 +87,10 @@ import Images self.updateBadge() } - UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert]) { (granted, _) in - if granted { - DispatchQueue.main.async { - UIApplication.shared.registerForRemoteNotifications() - } - } - } + // Silent CloudKit pushes don’t need notification permission. setBadgeCount does. + UIApplication.shared.registerForRemoteNotifications() + + UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert]) { _, _ in } UNUserNotificationCenter.current().delegate = self UserNotificationManager.shared.start() From 3039b3b6c9b1347dff249cb9bf3e85f460bc683c Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Wed, 16 Sep 2026 10:08:41 -0700 Subject: [PATCH 23/25] Use different keychain usernames. --- .../Feedly/FeedlyReauthorizationTests.swift | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/Modules/Account/Tests/AccountTests/Feedly/FeedlyReauthorizationTests.swift b/Modules/Account/Tests/AccountTests/Feedly/FeedlyReauthorizationTests.swift index d1e8bae6a..f377bb949 100644 --- a/Modules/Account/Tests/AccountTests/Feedly/FeedlyReauthorizationTests.swift +++ b/Modules/Account/Tests/AccountTests/Feedly/FeedlyReauthorizationTests.swift @@ -5,6 +5,7 @@ // Created by Brent Simmons on 9/16/26. // +import Foundation import Testing import RSWeb import Secrets @@ -24,7 +25,10 @@ import Secrets TestAccountManager.shared.deleteAccount(account) } let delegate = try #require(account.delegate as? FeedlyAccountDelegate) - try account.storeCredentials(Credentials(type: .oauthRefreshToken, username: "someone", secret: "rejected-token")) + + // Unique per test — keychain entries are keyed by server and username. + let username = UUID().uuidString + try account.storeCredentials(Credentials(type: .oauthRefreshToken, username: username, secret: "rejected-token")) let firstResult = await delegate.reauthorizeFeedlyAPICaller() #expect(firstResult == false) @@ -45,12 +49,15 @@ import Secrets TestAccountManager.shared.deleteAccount(account) } let delegate = try #require(account.delegate as? FeedlyAccountDelegate) - try account.storeCredentials(Credentials(type: .oauthRefreshToken, username: "someone", secret: "rejected-token")) + + // Unique per test — keychain entries are keyed by server and username. + let username = UUID().uuidString + try account.storeCredentials(Credentials(type: .oauthRefreshToken, username: username, secret: "rejected-token")) _ = await delegate.reauthorizeFeedlyAPICaller() #expect(TestingURLProtocol.requestCount(forURLContaining: Self.tokenEndpoint) == 1) - try account.storeCredentials(Credentials(type: .oauthAccessToken, username: "someone", secret: "fresh-token")) + try account.storeCredentials(Credentials(type: .oauthAccessToken, username: username, secret: "fresh-token")) _ = await delegate.reauthorizeFeedlyAPICaller() #expect(TestingURLProtocol.requestCount(forURLContaining: Self.tokenEndpoint) == 2) From e88ce512143eb9ada882fb01703eef1571c9616c Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Wed, 16 Sep 2026 10:08:49 -0700 Subject: [PATCH 24/25] Move location of test folders. --- .../Tests/AccountTests/TestAccountManager.swift | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/Modules/Account/Tests/AccountTests/TestAccountManager.swift b/Modules/Account/Tests/AccountTests/TestAccountManager.swift index 9cc1c13bd..2f035dbf1 100644 --- a/Modules/Account/Tests/AccountTests/TestAccountManager.swift +++ b/Modules/Account/Tests/AccountTests/TestAccountManager.swift @@ -16,9 +16,9 @@ import Secrets nonisolated static let shared = TestAccountManager() - var accountsFolder: URL { - return try! FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) - } + // Not Caches: macOS puts a `group:everyone deny delete` ACE on it, so test accounts + // created there can't be removed afterward. + private let accountsFolder = FileManager.default.temporaryDirectory.appendingPathComponent("NetNewsWireTestAccounts") func createAccount(type: AccountType, username: String? = nil, password: String? = nil) -> Account { @@ -46,13 +46,8 @@ import Secrets account.deleteSettings() - do { - try FileManager.default.removeItem(atPath: account.dataFolder) - } catch let error as CocoaError where error.code == .fileNoSuchFile { - - } catch { - assertionFailure("Could not delete folder at: \(account.dataFolder) because \(error)") - abort() - } + // Cleanup failing is not a test failure, and aborting here would take every + // other test in the process down with it. + try? FileManager.default.removeItem(atPath: account.dataFolder) } } From 8177f94428a070cd3a4bc38dca70c7956bb09eec Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Wed, 16 Sep 2026 10:33:58 -0700 Subject: [PATCH 25/25] Keep focus on account name field while typing. Fixes #5434. --- .../AccountsDetailViewController.swift | 2 +- .../AccountsPreferencesViewController.swift | 30 +++++++++++++++---- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/Mac/Preferences/Accounts/AccountsDetailViewController.swift b/Mac/Preferences/Accounts/AccountsDetailViewController.swift index 2c3b4a6ee..0a6f69cee 100644 --- a/Mac/Preferences/Accounts/AccountsDetailViewController.swift +++ b/Mac/Preferences/Accounts/AccountsDetailViewController.swift @@ -12,7 +12,7 @@ import Account final class AccountsDetailViewController: NSViewController { - private let account: Account + let account: Account private var accountsWindowController: NSWindowController? init(account: Account) { diff --git a/Mac/Preferences/Accounts/AccountsPreferencesViewController.swift b/Mac/Preferences/Accounts/AccountsPreferencesViewController.swift index 569beeaaf..49821b188 100644 --- a/Mac/Preferences/Accounts/AccountsPreferencesViewController.swift +++ b/Mac/Preferences/Accounts/AccountsPreferencesViewController.swift @@ -27,6 +27,7 @@ final class AccountsPreferencesViewController: NSViewController { var addAccountsViewController: NSHostingController? private var sortedAccounts = [Account]() + private var isReloadingTable = false private var selectedAccount: Account? { account(at: tableView.selectedRow) } @@ -144,12 +145,11 @@ extension AccountsPreferencesViewController: NSTableViewDelegate { func tableViewSelectionDidChange(_ notification: Notification) { updateDeleteButtonState() - if let selectedAccount { - let controller = AccountsDetailViewController(account: selectedAccount) - showController(controller) - } else { - hideController() + // A reload can report its selection more than once, so reloadTable(selecting:) updates the detail view when it settles. + if isReloadingTable { + return } + updateDetailView() } } @@ -245,11 +245,31 @@ private extension AccountsPreferencesViewController { func reloadTable(selecting accountToSelect: Account?) { updateSortedAccounts() + + isReloadingTable = true tableView.reloadData() if let accountToSelect, let row = sortedAccounts.firstIndex(of: accountToSelect) { tableView.selectRowIndexes(IndexSet(integer: row), byExtendingSelection: false) } + isReloadingTable = false + updateDeleteButtonState() + updateDetailView() + } + + /// Reuses the existing detail view controller when it's already showing the selected account, so an in-progress edit isn't destroyed. + func updateDetailView() { + guard let selectedAccount else { + hideController() + return + } + + let accountShowingInDetailView = (children.first as? AccountsDetailViewController)?.account + if accountShowingInDetailView == selectedAccount { + return + } + + showController(AccountsDetailViewController(account: selectedAccount)) } func updateDeleteButtonState() {