Convert RSWeb to approachable concurrency.

This commit is contained in:
Brent Simmons committed 2025-11-13 20:26:40 -08:00
1 parent 1f51119aa3
commit 378929a674
46 files changed
+272 -221

No files matched your search

+8 -6
View File
@@ -9,7 +9,7 @@
import Foundation
import RSWeb
struct Browser {
@MainActor struct Browser {
/// The user-specified default browser for opening web pages.
///
@@ -53,11 +53,13 @@ struct Browser {
}
NSWorkspace.shared.open(preparedURL, configuration: configuration) { (runningApplication, error) in
guard error != nil else { return }
if let defaultBrowser = defaultBrowser {
defaultBrowser.openURL(url, inBackground: inBackground)
} else {
MacWebBrowser.openURL(url, inBackground: inBackground)
Task { @MainActor in
guard error != nil else { return }
if let defaultBrowser = defaultBrowser {
defaultBrowser.openURL(url, inBackground: inBackground)
} else {
MacWebBrowser.openURL(url, inBackground: inBackground)
}
}
}
}
@@ -1129,7 +1129,7 @@ public final class Account: DisplayNameProvider, UnreadCountProvider, Container,
return
}
refreshInProgress = refreshProgress.numberRemaining > 0
refreshInProgress = !refreshProgress.isComplete
NotificationCenter.default.post(name: .AccountRefreshProgressDidChange, object: self)
}
@@ -135,7 +135,7 @@ enum CloudKitAccountDelegateError: LocalizedError {
}
let normalizedItems = OPMLNormalizer.normalize(opmlItems)
syncProgress.addToNumberOfTasksAndRemaining(1)
syncProgress.addTask()
defer { syncProgress.completeTask() }
do {
@@ -158,7 +158,7 @@ enum CloudKitAccountDelegateError: LocalizedError {
@MainActor func renameFeed(for account: Account, with feed: Feed, to name: String) async throws {
let editedName = name.isEmpty ? nil : name
syncProgress.addToNumberOfTasksAndRemaining(1)
syncProgress.addTask()
defer {
syncProgress.completeTask()
}
@@ -190,7 +190,7 @@ enum CloudKitAccountDelegateError: LocalizedError {
}
@MainActor func moveFeed(account: Account, feed: Feed, sourceContainer: Container, destinationContainer: Container) async throws {
syncProgress.addToNumberOfTasksAndRemaining(1)
syncProgress.addTask()
defer { syncProgress.completeTask() }
do {
@@ -204,7 +204,7 @@ enum CloudKitAccountDelegateError: LocalizedError {
}
@MainActor func addFeed(account: Account, feed: Feed, container: Container) async throws {
syncProgress.addToNumberOfTasksAndRemaining(1)
syncProgress.addTask()
defer { syncProgress.completeTask() }
do {
@@ -221,7 +221,7 @@ enum CloudKitAccountDelegateError: LocalizedError {
}
@MainActor func createFolder(for account: Account, name: String) async throws -> Folder {
syncProgress.addToNumberOfTasksAndRemaining(1)
syncProgress.addTask()
defer { syncProgress.completeTask() }
do {
@@ -238,7 +238,7 @@ enum CloudKitAccountDelegateError: LocalizedError {
}
@MainActor func renameFolder(for account: Account, with folder: Folder, to name: String) async throws {
syncProgress.addToNumberOfTasksAndRemaining(1)
syncProgress.addTask()
defer { syncProgress.completeTask() }
do {
@@ -251,7 +251,7 @@ enum CloudKitAccountDelegateError: LocalizedError {
}
@MainActor func removeFolder(for account: Account, with folder: Folder) async throws {
syncProgress.addToNumberOfTasksAndRemaining(2)
syncProgress.addTask()
let feedExternalIDs: [String]
do {
@@ -301,7 +301,7 @@ enum CloudKitAccountDelegateError: LocalizedError {
}
let feedsToRestore = folder.topLevelFeeds
syncProgress.addToNumberOfTasksAndRemaining(1 + feedsToRestore.count)
syncProgress.addTasks(1 + feedsToRestore.count)
do {
let externalID = try await accountZone.createFolder(name: name)
@@ -402,13 +402,13 @@ private extension CloudKitAccountDelegate {
func updateRefreshProgress() {
refreshProgress.numberOfTasks = refresher.downloadProgress.numberOfTasks + syncProgress.numberOfTasks
refreshProgress.numberRemaining = refresher.downloadProgress.numberRemaining + syncProgress.numberRemaining
// refreshProgress.numberOfTasks = refresher.downloadProgress.numberOfTasks + syncProgress.numberOfTasks
// refreshProgress.numberRemaining = refresher.downloadProgress.numberRemaining + syncProgress.numberRemaining
// Complete?
if refreshProgress.numberOfTasks > 0 && refreshProgress.numberRemaining < 1 {
refresher.downloadProgress.numberOfTasks = 0
syncProgress.numberOfTasks = 0
if refreshProgress.isComplete {
refresher.downloadProgress.reset()
syncProgress.reset()
}
}
@@ -436,7 +436,7 @@ private extension CloudKitAccountDelegate {
}
@MainActor func performRefreshAll(for account: Account, sendArticleStatus: Bool) async throws {
syncProgress.addToNumberOfTasksAndRemaining(3)
syncProgress.addTasks(3)
do {
try await accountZone.fetchChangesInZone()
@@ -463,7 +463,7 @@ private extension CloudKitAccountDelegate {
}
@MainActor func createRSSFeed(for account: Account, url: URL, editedName: String?, container: Container, validateFeed: Bool) async throws -> Feed {
syncProgress.addToNumberOfTasksAndRemaining(5)
syncProgress.addTasks(5)
do {
let feedSpecifiers = try await FeedFinder.find(url: url)
@@ -647,7 +647,7 @@ private extension CloudKitAccountDelegate {
}
@MainActor func removeFeedFromCloud(for account: Account, with feed: Feed, from container: Container) async throws {
syncProgress.addToNumberOfTasksAndRemaining(2)
syncProgress.addTasks(2)
do {
let _ = try await accountZone.removeFeed(feed, from: container)
@@ -40,7 +40,7 @@ final class CloudKitSendStatusOperation: MainThreadOperation, @unchecked Sendabl
do {
let count = (try await syncDatabase.selectPendingCount()) ?? 0
let ticks = count / blockSize
refreshProgress?.addToNumberOfTasksAndRemaining(ticks)
refreshProgress?.addTasks(ticks)
selectForProcessing()
} catch {
Self.logger.debug("iCloud: Send status count pending error: \(error.localizedDescription)")
@@ -56,9 +56,10 @@ public final class CombinedRefreshProgress {
let downloadProgresses = AccountManager.shared.activeAccounts.map { $0.refreshProgress }
for downloadProgress in downloadProgresses {
updatedNumberOfTasks += downloadProgress.numberOfTasks
updatedNumberRemaining += downloadProgress.numberRemaining
updatedNumberCompleted += downloadProgress.numberCompleted
let progressInfo = downloadProgress.progressInfo
updatedNumberOfTasks += progressInfo.numberOfTasks
updatedNumberRemaining += progressInfo.numberRemaining
updatedNumberCompleted += progressInfo.numberCompleted
}
if updatedNumberOfTasks > numberOfTasks {
@@ -72,7 +72,7 @@ final class FeedbinAccountDelegate: AccountDelegate {
@MainActor func refreshAll(for account: Account) async throws {
refreshProgress.reset()
refreshProgress.addToNumberOfTasksAndRemaining(5)
refreshProgress.addTasks(5)
do {
try await refreshAccount(account)
@@ -146,7 +146,7 @@ final class FeedbinAccountDelegate: AccountDelegate {
Self.logger.info("Feedbin: Did begin importing OPML")
isOPMLImportInProgress = true
refreshProgress.addToNumberOfTasksAndRemaining(1)
refreshProgress.addTask()
defer {
isOPMLImportInProgress = false
refreshProgress.completeTask()
@@ -179,7 +179,7 @@ final class FeedbinAccountDelegate: AccountDelegate {
return
}
refreshProgress.addToNumberOfTasksAndRemaining(1)
refreshProgress.addTask()
defer {
refreshProgress.completeTask()
}
@@ -200,7 +200,7 @@ final class FeedbinAccountDelegate: AccountDelegate {
return
}
refreshProgress.addToNumberOfTasksAndRemaining(folder.topLevelFeeds.count)
refreshProgress.addTasks(folder.topLevelFeeds.count)
for feed in folder.topLevelFeeds {
defer {
@@ -233,7 +233,7 @@ final class FeedbinAccountDelegate: AccountDelegate {
@discardableResult
@MainActor func createFeed(for account: Account, url urlString: String, name: String?, container: Container, validateFeed: Bool) async throws -> Feed {
refreshProgress.addToNumberOfTasksAndRemaining(1)
refreshProgress.addTask()
defer { refreshProgress.completeTask() }
do {
@@ -259,7 +259,7 @@ final class FeedbinAccountDelegate: AccountDelegate {
throw AccountError.invalidParameter
}
refreshProgress.addToNumberOfTasksAndRemaining(1)
refreshProgress.addTask()
defer {
refreshProgress.completeTask()
}
@@ -292,7 +292,7 @@ final class FeedbinAccountDelegate: AccountDelegate {
@MainActor func addFeed(account: Account, feed: Feed, container: Container) async throws {
if let folder = container as? Folder, let feedID = Int(feed.feedID) {
refreshProgress.addToNumberOfTasksAndRemaining(1)
refreshProgress.addTask()
defer { refreshProgress.completeTask() }
do {
@@ -739,7 +739,7 @@ private extension FeedbinAccountDelegate {
let (entries, page, updateFetchDate, lastPageNumber) = try await caller.retrieveEntries()
if let last = lastPageNumber {
refreshProgress.addToNumberOfTasksAndRemaining(last - 1)
refreshProgress.addTasks(last - 1)
}
try await processEntries(account: account, entries: entries)
@@ -874,7 +874,7 @@ private extension FeedbinAccountDelegate {
@MainActor func deleteTagging(for account: Account, with feed: Feed, from container: Container?) async throws {
if let folder = container as? Folder, let feedTaggingID = feed.folderRelationship?[folder.name ?? ""] {
refreshProgress.addToNumberOfTasksAndRemaining(1)
refreshProgress.addTask()
defer {
refreshProgress.completeTask()
}
@@ -900,7 +900,7 @@ private extension FeedbinAccountDelegate {
throw AccountError.invalidParameter
}
refreshProgress.addToNumberOfTasksAndRemaining(1)
refreshProgress.addTask()
defer { refreshProgress.completeTask() }
do {
@@ -84,7 +84,7 @@ final class FeedlyAPICaller {
isSuspended = false
}
func send<R: Decodable>(request: URLRequest, resultType: R.Type, dateDecoding: JSONDecoder.DateDecodingStrategy = .iso8601, keyDecoding: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys, completion: @escaping (Result<(HTTPURLResponse, R?), Error>) -> Void) {
func send<R: Decodable & Sendable>(request: URLRequest, resultType: R.Type, dateDecoding: JSONDecoder.DateDecodingStrategy = .iso8601, keyDecoding: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys, completion: @escaping (Result<(HTTPURLResponse, R?), Error>) -> Void) {
transport.send(request: request, resultType: resultType, dateDecoding: dateDecoding, keyDecoding: keyDecoding) { [weak self] result in
Task { @MainActor in
assert(Thread.isMainThread)
@@ -105,7 +105,7 @@ final class FeedlyAPICaller {
/// Capture the credentials before the reauthorization to check for a change.
let credentialsBefore = self.credentials
delegate.reauthorizeFeedlyAPICaller(self) { [weak self] isReauthorizedAndShouldRetry in
assert(Thread.isMainThread)
@@ -12,16 +12,16 @@ import Secrets
/// Models the access token response from Feedly.
/// https://developer.feedly.com/v3/auth/#exchanging-an-auth-code-for-a-refresh-token-and-an-access-token
public struct FeedlyOAuthAccessTokenResponse: Decodable, OAuthAccessTokenResponse {
nonisolated public struct FeedlyOAuthAccessTokenResponse: Decodable, OAuthAccessTokenResponse, Sendable {
/// The ID of the Feedly user.
public var id: String
public let id: String
// Required properties of the OAuth 2.0 Authorization Framework section 4.1.4.
public var accessToken: String
public var tokenType: String
public var expiresIn: Int
public var refreshToken: String?
public var scope: String
public let accessToken: String
public let tokenType: String
public let expiresIn: Int
public let refreshToken: String?
public let scope: String
}
extension FeedlyAccountDelegate: OAuthAuthorizationGranting {
@@ -246,7 +246,7 @@ import Secrets
Self.logger.info("Feedly: Begin importing OPML")
isOPMLImportInProgress = true
refreshProgress.addToNumberOfTasksAndRemaining(1)
refreshProgress.addTask()
caller.importOpml(data) { result in
switch result {
@@ -280,7 +280,7 @@ import Secrets
@MainActor func createFolder(for account: Account, name: String, completion: @escaping (Result<Folder, Error>) -> Void) {
let progress = refreshProgress
progress.addToNumberOfTasksAndRemaining(1)
progress.addTask()
caller.createCollection(named: name) { result in
progress.completeTask()
@@ -347,8 +347,8 @@ import Secrets
}
let progress = refreshProgress
progress.addToNumberOfTasksAndRemaining(1)
progress.addTask()
caller.deleteCollection(with: id) { result in
progress.completeTask()
@@ -8,7 +8,7 @@
import Foundation
struct FeedlyCollection: Codable {
nonisolated struct FeedlyCollection: Codable, Sendable {
let feeds: [FeedlyFeed]
let label: String
let id: String
@@ -8,7 +8,7 @@
import Foundation
struct FeedlyEntry: Decodable {
nonisolated struct FeedlyEntry: Decodable, Sendable {
/// the unique, immutable ID for this particular article.
let id: String
@@ -8,7 +8,7 @@
import Foundation
struct FeedlyFeed: Codable {
nonisolated struct FeedlyFeed: Codable, Sendable {
let id: String
let title: String?
let updated: Date?
@@ -8,8 +8,7 @@
import Foundation
struct FeedlyFeedsSearchResponse: Decodable {
nonisolated struct FeedlyFeedsSearchResponse: Decodable, Sendable {
struct Feed: Decodable {
let title: String
let feedId: String
@@ -8,7 +8,7 @@
import Foundation
struct FeedlyStream: Decodable {
nonisolated struct FeedlyStream: Decodable, Sendable {
let id: String
/// Of the most recent entry for this stream (regardless of continuation, newerThan, etc).
@@ -8,7 +8,7 @@
import Foundation
struct FeedlyStreamIds: Decodable {
nonisolated struct FeedlyStreamIds: Decodable, Sendable {
let continuation: String?
let ids: [String]
@@ -24,7 +24,7 @@ open class FeedlyOperation: MainThreadOperation, @unchecked Sendable {
var downloadProgress: DownloadProgress? {
didSet {
oldValue?.completeTask()
downloadProgress?.addToNumberOfTasksAndRemaining(1)
downloadProgress?.addTask()
}
}
@@ -354,7 +354,7 @@ import os.log
}
func downloadFeed(account: Account, feed: Feed, page: Int) async throws {
refreshProgress.addToNumberOfTasksAndRemaining(1)
refreshProgress.addTask()
defer {
refreshProgress.completeTask()
}
@@ -373,7 +373,7 @@ import os.log
}
func initialFeedDownload(account: Account, feed: Feed) async throws {
refreshProgress.addToNumberOfTasksAndRemaining(1)
refreshProgress.addTask()
defer {
refreshProgress.completeTask()
}
@@ -390,7 +390,7 @@ import os.log
throw AccountError.invalidParameter
}
refreshProgress.addToNumberOfTasksAndRemaining(1)
refreshProgress.addTask()
defer {
refreshProgress.completeTask()
}
@@ -63,7 +63,7 @@ import Secrets
func refreshAll(for account: Account) async throws {
refreshProgress.reset()
self.refreshProgress.addToNumberOfTasksAndRemaining(4)
self.refreshProgress.addTasks(4)
do {
try await refreshFeeds(for: account)
@@ -176,7 +176,7 @@ import Secrets
let storyHashes = try await caller.retrieveUnreadStoryHashes()
if let count = storyHashes?.count, count > 0 {
refreshProgress.addToNumberOfTasksAndRemaining((count - 1) / 100 + 1)
refreshProgress.addTasks((count - 1) / 100 + 1)
}
let storyHashesArray: [NewsBlurStoryHash] = {
@@ -239,7 +239,7 @@ import Secrets
}
@MainActor func createFolder(for account: Account, name: String) async throws -> Folder {
refreshProgress.addToNumberOfTasksAndRemaining(1)
refreshProgress.addTask()
defer {
refreshProgress.completeTask()
}
@@ -257,7 +257,7 @@ import Secrets
throw AccountError.invalidParameter
}
refreshProgress.addToNumberOfTasksAndRemaining(1)
refreshProgress.addTask()
defer {
refreshProgress.completeTask()
}
@@ -287,7 +287,7 @@ import Secrets
}
}
refreshProgress.addToNumberOfTasksAndRemaining(1)
refreshProgress.addTask()
defer {
refreshProgress.completeTask()
}
@@ -298,7 +298,7 @@ import Secrets
@discardableResult
@MainActor func createFeed(for account: Account, url urlString: String, name: String?, container: Container, validateFeed: Bool) async throws -> Feed {
refreshProgress.addToNumberOfTasksAndRemaining(1)
refreshProgress.addTask()
defer {
refreshProgress.completeTask()
}
@@ -321,7 +321,7 @@ import Secrets
throw AccountError.invalidParameter
}
refreshProgress.addToNumberOfTasksAndRemaining(1)
refreshProgress.addTask()
defer {
refreshProgress.completeTask()
}
@@ -358,7 +358,7 @@ import Secrets
throw AccountError.invalidParameter
}
refreshProgress.addToNumberOfTasksAndRemaining(1)
refreshProgress.addTask()
defer {
refreshProgress.completeTask()
}
@@ -106,7 +106,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
func refreshAll(for account: Account) async throws {
refreshProgress.addToNumberOfTasksAndRemaining(6)
refreshProgress.addTasks(6)
do {
try await refreshAccount(account)
@@ -219,7 +219,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
func renameFolder(for account: Account, with folder: Folder, to name: String) async throws {
refreshProgress.addToNumberOfTasksAndRemaining(1)
refreshProgress.addTask()
defer { refreshProgress.completeTask() }
do {
@@ -239,7 +239,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
if let subscriptionID = feed.externalID {
refreshProgress.addToNumberOfTasksAndRemaining(1)
refreshProgress.addTask()
do {
try await caller.deleteTagging(subscriptionID: subscriptionID, tagName: folder.nameForDisplay)
@@ -254,7 +254,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
} else {
if let subscriptionID = feed.externalID {
refreshProgress.addToNumberOfTasksAndRemaining(1)
refreshProgress.addTask()
do {
try await caller.deleteSubscription(subscriptionID: subscriptionID)
@@ -287,7 +287,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
throw AccountError.invalidParameter
}
refreshProgress.addToNumberOfTasksAndRemaining(2)
refreshProgress.addTasks(2)
do {
@@ -325,7 +325,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
throw AccountError.invalidParameter
}
refreshProgress.addToNumberOfTasksAndRemaining(1)
refreshProgress.addTask()
do {
try await caller.renameSubscription(subscriptionID: subscriptionID, newName: name)
@@ -343,7 +343,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
throw AccountError.invalidParameter
}
refreshProgress.addToNumberOfTasksAndRemaining(1)
refreshProgress.addTask()
defer { refreshProgress.completeTask()}
do {
@@ -370,7 +370,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
throw AccountError.invalidParameter
}
refreshProgress.addToNumberOfTasksAndRemaining(1)
refreshProgress.addTask()
defer { refreshProgress.completeTask() }
do {
@@ -387,7 +387,7 @@ final class ReaderAPIAccountDelegate: AccountDelegate {
if let folder = container as? Folder, let feedExternalID = feed.externalID {
refreshProgress.addToNumberOfTasksAndRemaining(1)
refreshProgress.addTask()
do {
@@ -727,7 +727,7 @@ private extension ReaderAPIAccountDelegate {
@discardableResult
func initialFeedDownload( account: Account, feed: Feed) async throws -> Feed {
refreshProgress.addToNumberOfTasksAndRemaining(5)
refreshProgress.addTasks(5)
// Download the initial articles
let articleIDs = try await caller.retrieveItemIDs(type: .allForFeed, feedID: feed.feedID)
@@ -760,7 +760,7 @@ private extension ReaderAPIAccountDelegate {
let articleIDs = Array(fetchedArticleIDs)
let chunkedArticleIDs = articleIDs.chunked(into: 150)
refreshProgress.addToNumberOfTasksAndRemaining(chunkedArticleIDs.count - 1)
refreshProgress.addTasks(chunkedArticleIDs.count - 1)
for chunk in chunkedArticleIDs {
@@ -0,0 +1,54 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2610"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES"
buildArchitectures = "Automatic">
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "RSWebTests"
BuildableName = "RSWebTests"
BlueprintName = "RSWebTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
+3 -1
View File
@@ -23,7 +23,9 @@ let package = Package(
],
swiftSettings: [
.unsafeFlags(["-warnings-as-errors"]),
.swiftLanguageMode(.v5)
.enableUpcomingFeature("NonisolatedNonsendingByDefault"),
.enableUpcomingFeature("InferIsolatedConformances"),
.defaultIsolation(MainActor.self)
]
),
.testTarget(
@@ -10,7 +10,7 @@ import Foundation
/// Basic Cache-Control handling — just the part we need,
/// which is to know when we got the response (dateCreated)
/// and when we can ask again (canResume).
public struct CacheControlInfo: Codable, Equatable {
nonisolated public struct CacheControlInfo: Codable, Equatable {
let dateCreated: Date
let maxAge: TimeInterval
@@ -42,7 +42,7 @@ public struct CacheControlInfo: Codable, Equatable {
}
}
private extension CacheControlInfo {
nonisolated private extension CacheControlInfo {
static let maxAgePrefix = "max-age="
static let maxAgePrefixCount = maxAgePrefix.count
@@ -8,7 +8,7 @@
import Foundation
public extension Dictionary where Key == String, Value == String {
nonisolated public extension Dictionary where Key == String, Value == String {
/// Translates a dictionary into a string like `foo=bar&param2=some%20thing`.
var urlQueryString: String? {
@@ -8,7 +8,7 @@
import Foundation
import RSCore
struct DownloadCacheRecord: CacheRecord {
nonisolated struct DownloadCacheRecord: CacheRecord, Sendable {
let dateCreated = Date()
let data: Data?
let response: URLResponse?
@@ -19,7 +19,7 @@ struct DownloadCacheRecord: CacheRecord {
}
}
final class DownloadCache: Sendable {
nonisolated final class DownloadCache: Sendable {
static let shared = DownloadCache()
private let cache = Cache<DownloadCacheRecord>(timeToLive: 60 * 13, timeBetweenCleanups: 60 * 2)
@@ -7,91 +7,113 @@
//
import Foundation
// Main thread only.
import Synchronization
public extension Notification.Name {
static let DownloadProgressDidChange = Notification.Name(rawValue: "DownloadProgressDidChange")
}
public final class DownloadProgress {
nonisolated public final class DownloadProgress: Sendable {
public struct ProgressInfo: Sendable {
public let numberOfTasks: Int
public let numberCompleted: Int
public let numberRemaining: Int
}
public var numberOfTasks = 0 {
didSet {
if numberOfTasks == 0 && numberRemaining != 0 {
numberRemaining = 0
}
if numberOfTasks != oldValue {
postDidChangeNotification()
}
private struct State {
var numberOfTasks = 0
var numberCompleted = 0
var numberRemaining: Int {
let n = numberOfTasks - numberCompleted
assert(n >= 0)
return n
}
init(_ numberOfTasks: Int) {
self.numberOfTasks = numberOfTasks
}
}
public var numberRemaining = 0 {
didSet {
if numberRemaining != oldValue {
postDidChangeNotification()
}
}
private let state: Mutex<State>
public init(numberOfTasks: Int) {
assert(numberOfTasks >= 0)
self.state = Mutex(State(numberOfTasks))
}
public var numberCompleted: Int {
var n = numberOfTasks - numberRemaining
if n < 0 {
n = 0
public var progressInfo: ProgressInfo {
var numberOfTasks = 0
var numberCompleted = 0
var numberRemaining = 0
state.withLock { state in
numberOfTasks = state.numberOfTasks
numberCompleted = state.numberCompleted
numberRemaining = state.numberRemaining
}
if n > numberOfTasks {
n = numberOfTasks
}
return n
return ProgressInfo(numberOfTasks: numberOfTasks,
numberCompleted: numberCompleted,
numberRemaining: numberRemaining)
}
public var isComplete: Bool {
assert(Thread.isMainThread)
return numberRemaining < 1
state.withLock { state in
state.numberRemaining < 1
}
}
public init(numberOfTasks: Int) {
assert(Thread.isMainThread)
self.numberOfTasks = numberOfTasks
public func addTask() {
addTasks(1)
}
public func addToNumberOfTasks(_ n: Int) {
assert(Thread.isMainThread)
numberOfTasks = numberOfTasks + n
}
public func addToNumberOfTasksAndRemaining(_ n: Int) {
assert(Thread.isMainThread)
numberOfTasks = numberOfTasks + n
numberRemaining = numberRemaining + n
public func addTasks(_ n: Int) {
assert(n > 0)
state.withLock { state in
state.numberOfTasks += n
}
postDidChangeNotification()
}
public func completeTask() {
assert(Thread.isMainThread)
if numberRemaining > 0 {
numberRemaining = numberRemaining - 1
}
completeTasks(1)
}
public func completeTasks(_ tasks: Int) {
assert(Thread.isMainThread)
if numberRemaining >= tasks {
numberRemaining = numberRemaining - tasks
state.withLock { state in
state.numberCompleted += tasks
assert(state.numberCompleted <= state.numberOfTasks)
}
postDidChangeNotification()
}
public func reset() {
assert(Thread.isMainThread)
numberRemaining = 0
numberOfTasks = 0
state.withLock { state in
var didChange = false
if state.numberOfTasks != 0 {
state.numberOfTasks = 0
didChange = true
}
if state.numberCompleted != 0 {
state.numberCompleted = 0
didChange = true
}
if didChange {
postDidChangeNotification()
}
}
}
}
// MARK: - Private
private extension DownloadProgress {
nonisolated private extension DownloadProgress {
func postDidChangeNotification() {
DispatchQueue.main.async {
@@ -105,7 +105,7 @@ struct HTTP4xxResponse {
// MARK: - URLSessionTaskDelegate
extension DownloadSession: URLSessionTaskDelegate {
extension DownloadSession: @preconcurrency URLSessionTaskDelegate {
public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
MainActor.assumeIsolated {
@@ -151,7 +151,7 @@ extension DownloadSession: URLSessionTaskDelegate {
// MARK: - URLSessionDataDelegate
extension DownloadSession: URLSessionDataDelegate {
extension DownloadSession: @preconcurrency URLSessionDataDelegate {
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
MainActor.assumeIsolated {
@@ -336,17 +336,17 @@ private extension DownloadSession {
// MARK: - Download Progress
@MainActor func updateDownloadProgress() {
downloadProgress.numberOfTasks = urlsInSession.count
let numberRemaining = tasksPending.count + tasksInProgress.count + queue.count
downloadProgress.numberRemaining = min(numberRemaining, downloadProgress.numberOfTasks)
// Complete?
if downloadProgress.numberOfTasks > 0 && downloadProgress.numberRemaining < 1 {
delegate.downloadSessionDidComplete(self)
urlsInSession.removeAll()
}
// TODO
// downloadProgress.numberOfTasks = urlsInSession.count
//
// let numberRemaining = tasksPending.count + tasksInProgress.count + queue.count
// downloadProgress.numberRemaining = min(numberRemaining, downloadProgress.numberOfTasks)
//
// // Complete?
// if downloadProgress.numberOfTasks > 0 && downloadProgress.numberRemaining < 1 {
// delegate.downloadSessionDidComplete(self)
// urlsInSession.removeAll()
// }
}
// MARK: - 429 Too Many Requests
+1 -1
View File
@@ -15,7 +15,7 @@ public typealias DownloadCallback = @MainActor (Data?, URLResponse?, Error?) ->
/// Simple downloader, for a one-shot download like an image
/// or a web page. For a download-feeds session, see DownloadSession.
/// Caches response for a short time for GET requests. May return cached response.
@MainActor public final class Downloader {
public final class Downloader {
public static let shared = Downloader()
private let urlSession: URLSession
@@ -11,10 +11,10 @@ import RSCore
public extension Notification.Name {
// Sent when HTMLMetadata is cached. Posted on any thread.
static let htmlMetadataAvailable = Notification.Name("htmlMetadataAvailable")
nonisolated static let htmlMetadataAvailable = Notification.Name("htmlMetadataAvailable")
}
public final class HTMLMetadataCache: Sendable {
nonisolated public final class HTMLMetadataCache: Sendable {
static let shared = HTMLMetadataCache()
@@ -12,7 +12,7 @@ import RSParser
// To get a notification when HTMLMetadata is cached, see HTMLMetadataCache.
public final class HTMLMetadataDownloader: Sendable {
nonisolated public final class HTMLMetadataDownloader: Sendable {
public static let shared = HTMLMetadataDownloader()
@@ -40,7 +40,7 @@ public final class HTMLMetadataDownloader: Sendable {
}
}
private extension HTMLMetadataDownloader {
nonisolated private extension HTMLMetadataDownloader {
private static let specialCasesToSkip = [SpecialCase.rachelByTheBayHostName, SpecialCase.openRSSOrgHostName]
@@ -8,7 +8,7 @@
import Foundation
public struct HTTPConditionalGetInfo: Codable, Equatable {
nonisolated public struct HTTPConditionalGetInfo: Codable, Equatable {
public let lastModified: String?
public let etag: String?
@@ -8,7 +8,7 @@
import Foundation
public struct HTTPDateInfo: Codable, Equatable {
nonisolated public struct HTTPDateInfo: Codable, Equatable {
private static let formatter: DateFormatter = {
let dateFormatter = DateFormatter()
+1 -2
View File
@@ -8,8 +8,7 @@
import Foundation
public struct HTTPMethod {
nonisolated public struct HTTPMethod {
public static let get = "GET"
public static let post = "POST"
public static let put = "PUT"
@@ -8,7 +8,7 @@
import Foundation
public struct HTTPRequestHeader {
nonisolated public struct HTTPRequestHeader {
public static let userAgent = "User-Agent"
public static let authorization = "Authorization"
@@ -8,7 +8,7 @@
import Foundation
public struct HTTPResponseHeader {
nonisolated public struct HTTPResponseHeader: Sendable {
public static let contentType = "Content-Type"
public static let location = "Location"
+2 -2
View File
@@ -8,7 +8,7 @@
import Foundation
public struct MimeType {
nonisolated public struct MimeType: Sendable {
// This could certainly use expansion.
@@ -21,7 +21,7 @@ public struct MimeType {
public static let formURLEncoded = "application/x-www-form-urlencoded"
}
public extension String {
nonisolated public extension String {
func isMimeTypeImage() -> Bool {
@@ -9,7 +9,7 @@ import Foundation
import Network
import os
public final class NetworkMonitor: Sendable {
nonisolated public final class NetworkMonitor: Sendable {
public static let shared = NetworkMonitor()
private let monitor: NWPathMonitor
@@ -8,9 +8,9 @@
import Foundation
import os
public let localeForLowercasing = Locale(identifier: "en_US")
nonisolated public let localeForLowercasing = Locale(identifier: "en_US")
public struct SpecialCase {
nonisolated public struct SpecialCase {
public static let rachelByTheBayHostName = "rachelbythebay.com"
public static let openRSSOrgHostName = "openrss.org"
@@ -26,7 +26,7 @@ public struct SpecialCase {
}
extension URL {
nonisolated extension URL {
public var isOpenRSSOrgURL: Bool {
guard let host = host() else {
@@ -43,7 +43,7 @@ extension URL {
}
}
extension Set where Element == URL {
nonisolated extension Set where Element == URL {
func byRemovingOpenRSSOrgURLs() -> Set<URL> {
filter { !$0.isOpenRSSOrgURL }
@@ -73,7 +73,7 @@ extension Set where Element == URL {
}
}
extension URLRequest {
nonisolated extension URLRequest {
mutating func addSpecialCaseUserAgentIfNeeded() {
guard let url else {
@@ -86,7 +86,7 @@ extension URLRequest {
}
}
extension UserAgent {
nonisolated extension UserAgent {
static let extendedUserAgent = {
#if os(iOS)
@@ -8,7 +8,7 @@
import Foundation
public extension String {
nonisolated public extension String {
/// Escapes special HTML characters.
///
@@ -8,7 +8,7 @@
import Foundation
public extension URLResponse {
nonisolated public extension URLResponse {
var statusIsOK: Bool {
return forcedStatusCode >= 200 && forcedStatusCode <= 299
@@ -25,7 +25,7 @@ public extension URLResponse {
}
}
public extension HTTPURLResponse {
nonisolated public extension HTTPURLResponse {
func valueForHTTPHeaderField(_ headerField: String) -> String? {
+1 -1
View File
@@ -8,7 +8,7 @@
import Foundation
public struct UserAgent {
nonisolated public struct UserAgent {
public static func fromInfoPlist() -> String? {
@@ -9,7 +9,7 @@
import Foundation
public enum TransportError: LocalizedError {
nonisolated public enum TransportError: LocalizedError, Sendable {
case noData
case noURL
case suspended
@@ -114,7 +114,7 @@ public enum TransportError: LocalizedError {
}
public protocol Transport {
nonisolated public protocol Transport {
/// Cancels all pending requests
func cancelAll()
@@ -124,23 +124,23 @@ public protocol Transport {
func send(request: URLRequest) async throws -> (HTTPURLResponse, Data?)
/// Sends URLRequest and returns the HTTP headers and the data payload.
func send(request: URLRequest, completion: @escaping (Result<(HTTPURLResponse, Data?), Error>) -> Void)
func send(request: URLRequest, completion: @escaping @Sendable (Result<(HTTPURLResponse, Data?), Error>) -> Void)
/// Sends URLRequest that doesn't require any result information.
func send(request: URLRequest, method: String) async throws
/// Sends URLRequest that doesn't require any result information.
func send(request: URLRequest, method: String, completion: @escaping (Result<Void, Error>) -> Void)
func send(request: URLRequest, method: String, completion: @escaping @Sendable (Result<Void, Error>) -> Void)
/// Sends URLRequest with a data payload and returns the HTTP headers and the data payload.
func send(request: URLRequest, method: String, payload: Data) async throws -> (HTTPURLResponse, Data?)
/// Sends URLRequest with a data payload and returns the HTTP headers and the data payload.
func send(request: URLRequest, method: String, payload: Data, completion: @escaping (Result<(HTTPURLResponse, Data?), Error>) -> Void)
func send(request: URLRequest, method: String, payload: Data, completion: @escaping @Sendable (Result<(HTTPURLResponse, Data?), Error>) -> Void)
}
extension URLSession: Transport {
nonisolated extension URLSession: Transport {
public func cancelAll() {
getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in
@@ -158,7 +158,7 @@ extension URLSession: Transport {
}
}
public func send(request: URLRequest, completion: @escaping (Result<(HTTPURLResponse, Data?), Error>) -> Void) {
public func send(request: URLRequest, completion: @escaping @Sendable (Result<(HTTPURLResponse, Data?), Error>) -> Void) {
let task = self.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
if let error = error {
@@ -188,7 +188,7 @@ extension URLSession: Transport {
}
}
public func send(request: URLRequest, method: String, completion: @escaping (Result<Void, Error>) -> Void) {
public func send(request: URLRequest, method: String, completion: @escaping @Sendable (Result<Void, Error>) -> Void) {
var sendRequest = request
sendRequest.httpMethod = method
@@ -222,7 +222,7 @@ extension URLSession: Transport {
}
}
public func send(request: URLRequest, method: String, payload: Data, completion: @escaping (Result<(HTTPURLResponse, Data?), Error>) -> Void) {
public func send(request: URLRequest, method: String, payload: Data, completion: @escaping @Sendable (Result<(HTTPURLResponse, Data?), Error>) -> Void) {
var sendRequest = request
sendRequest.httpMethod = method
@@ -8,7 +8,7 @@
import Foundation
extension Transport {
nonisolated extension Transport {
/// Send an HTTP GET and return JSON object(s)
public func send<R: Decodable & Sendable>(request: URLRequest, resultType: R.Type, dateDecoding: JSONDecoder.DateDecodingStrategy = .iso8601, keyDecoding: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys) async throws -> (HTTPURLResponse, R?) {
@@ -22,7 +22,7 @@ extension Transport {
/**
Sends an HTTP get and returns JSON object(s)
*/
public func send<R: Decodable & Sendable>(request: URLRequest, resultType: R.Type, dateDecoding: JSONDecoder.DateDecodingStrategy = .iso8601, keyDecoding: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys, completion: @escaping (Result<(HTTPURLResponse, R?), Error>) -> Void) {
public func send<R: Decodable & Sendable>(request: URLRequest, resultType: R.Type, dateDecoding: JSONDecoder.DateDecodingStrategy = .iso8601, keyDecoding: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys, completion: @escaping @Sendable (Result<(HTTPURLResponse, R?), Error>) -> Void) {
send(request: request) { result in
DispatchQueue.main.async {
@@ -77,7 +77,7 @@ extension Transport {
/**
Sends the specified HTTP method with a JSON payload.
*/
public func send<P: Encodable>(request: URLRequest, method: String, payload: P, completion: @escaping (Result<Void, Error>) -> Void) {
public func send<P: Encodable>(request: URLRequest, method: String, payload: P, completion: @escaping @Sendable (Result<Void, Error>) -> Void) {
var postRequest = request
postRequest.addValue("application/json; charset=utf-8", forHTTPHeaderField: HTTPRequestHeader.contentType)
@@ -105,7 +105,7 @@ extension Transport {
/**
Sends the specified HTTP method with a JSON payload and returns JSON object(s).
*/
public func send<P: Encodable, R: Decodable>(request: URLRequest, method: String, payload: P, resultType: R.Type, dateDecoding: JSONDecoder.DateDecodingStrategy = .iso8601, keyDecoding: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys, completion: @escaping (Result<(HTTPURLResponse, R?), Error>) -> Void) {
public func send<P: Encodable, R: Decodable>(request: URLRequest, method: String, payload: P, resultType: R.Type, dateDecoding: JSONDecoder.DateDecodingStrategy = .iso8601, keyDecoding: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys, completion: @escaping @Sendable (Result<(HTTPURLResponse, R?), Error>) -> Void) {
var postRequest = request
postRequest.addValue("application/json; charset=utf-8", forHTTPHeaderField: HTTPRequestHeader.contentType)
@@ -143,7 +143,7 @@ extension Transport {
}
}
public func send<R: Decodable>(request: URLRequest, method: String, data: Data, resultType: R.Type, dateDecoding: JSONDecoder.DateDecodingStrategy = .iso8601, keyDecoding: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys) async throws -> (HTTPURLResponse, R?) {
public func send<R: Decodable & Sendable>(request: URLRequest, method: String, data: Data, resultType: R.Type, dateDecoding: JSONDecoder.DateDecodingStrategy = .iso8601, keyDecoding: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys) async throws -> (HTTPURLResponse, R?) {
try await withCheckedThrowingContinuation { continuation in
self.send(request: request, method: method, data: data, resultType: resultType, dateDecoding: dateDecoding, keyDecoding: keyDecoding) { result in
@@ -161,7 +161,7 @@ extension Transport {
/**
Sends the specified HTTP method with a Raw payload and returns JSON object(s).
*/
public func send<R: Decodable>(request: URLRequest, method: String, data: Data, resultType: R.Type, dateDecoding: JSONDecoder.DateDecodingStrategy = .iso8601, keyDecoding: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys, completion: @escaping (Result<(HTTPURLResponse, R?), Error>) -> Void) {
public func send<R: Decodable>(request: URLRequest, method: String, data: Data, resultType: R.Type, dateDecoding: JSONDecoder.DateDecodingStrategy = .iso8601, keyDecoding: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys, completion: @escaping @Sendable (Result<(HTTPURLResponse, R?), Error>) -> Void) {
send(request: request, method: method, payload: data) { result in
DispatchQueue.main.async {
@@ -7,11 +7,11 @@
//
import XCTest
@testable import RSWeb
final class DictionaryTests: XCTestCase {
func testSimpleQueryString() {
let d = ["foo": "bar", "param1": "This is a value."]
let s = d.urlQueryString
@@ -19,7 +19,6 @@ final class DictionaryTests: XCTestCase {
}
func testQueryStringWithAmpersand() {
let d = ["fo&o": "bar", "param1": "This is a&value."]
let s = d.urlQueryString
@@ -27,19 +26,16 @@ final class DictionaryTests: XCTestCase {
}
func testQueryStringWithAccentedCharacters() {
let d = ["fée": "bør"]
let s = d.urlQueryString
XCTAssertTrue(s == "f%C3%A9e=b%C3%B8r")
XCTAssertEqual(s, "f%C3%A9e=b%C3%B8r")
}
func testQueryStringWithEmoji() {
let d = ["🌴e": "bar🎩🌴"]
let s = d.urlQueryString
XCTAssertTrue(s == "%F0%9F%8C%B4e=bar%F0%9F%8E%A9%F0%9F%8C%B4")
XCTAssertEqual(s, "%F0%9F%8C%B4e=bar%F0%9F%8E%A9%F0%9F%8C%B4")
}
}
@@ -1,23 +0,0 @@
//
// RSWebTests.swift
// RSWebTests
//
// Created by Brent Simmons on 12/22/16.
// Copyright © 2016 Ranchero Software, LLC. All rights reserved.
//
import XCTest
@testable import RSWeb
final class RSWebTests: XCTestCase {
#if os(macOS)
func testAllBrowsers() {
let browsers = MacWebBrowser.sortedBrowsers()
XCTAssertNotNil(browsers);
}
#endif
}
@@ -7,13 +7,12 @@
//
import XCTest
@testable import RSWeb
final class StringTests: XCTestCase {
func testHTMLEscaping() {
let s = #"<foo>"bar"&'baz'"#.escapedHTML
XCTAssertEqual(s, "&lt;foo&gt;&quot;bar&quot;&amp;&apos;baz&apos;")
}
}
+1 -1
View File
@@ -21,7 +21,7 @@ enum HelpURL: String {
case privacyPolicy = "https://netnewswire.com/privacypolicy.html"
#if os(macOS)
func open() {
@MainActor func open() {
Browser.open(self.rawValue, inBackground: false)
}
#endif