mirror of
https://github.com/Ranchero-Software/NetNewsWire
synced 2026-11-28 08:17:16 +00:00
Work around unexplainable Swift concurrency crash by creating/running the session off the main thread. Fixes #4937.
This commit is contained in:
1 parent
3792cd3eda
commit
acfee014de
1 file changed
+74
-42
@@ -7,7 +7,8 @@
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import AuthenticationServices
|
||||
@preconcurrency import AuthenticationServices
|
||||
import os
|
||||
import RSCore
|
||||
|
||||
@MainActor public protocol OAuthAccountAuthorizationOperationDelegate: AnyObject {
|
||||
@@ -23,6 +24,18 @@ public enum OAuthAccountAuthorizationOperationError: LocalizedError, Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Documentation does not say on why `ASWebAuthenticationSession.start` or `canStart` might return false.
|
||||
/// Perhaps it has something to do with an inter-process communication failure?
|
||||
/// No browsers installed? No browsers that support web authentication?
|
||||
struct UnableToStartASWebAuthenticationSessionError: LocalizedError, Sendable {
|
||||
let errorDescription: String? = NSLocalizedString(
|
||||
"Unable to start a web authentication session with the default web browser.",
|
||||
comment: "OAuth - error description - unable to authorize because ASWebAuthenticationSession did not start.")
|
||||
let recoverySuggestion: String? = NSLocalizedString(
|
||||
"Check your default web browser in System Preferences or change it to Safari and try again.",
|
||||
comment: "OAuth - recovery suggestion - ensure browser selected supports web authentication.")
|
||||
}
|
||||
|
||||
@objc nonisolated final class PresentationAnchorProvider: NSObject, ASWebAuthenticationPresentationContextProviding {
|
||||
nonisolated(unsafe) var presentationAnchor: ASPresentationAnchor?
|
||||
|
||||
@@ -50,9 +63,10 @@ public final class OAuthAccountAuthorizationOperation: MainThreadOperation, @unc
|
||||
|
||||
private let accountType: AccountType
|
||||
private let oauthClient: OAuthAuthorizationClient
|
||||
private let anchorProvider = PresentationAnchorProvider()
|
||||
private var session: ASWebAuthenticationSession?
|
||||
nonisolated(unsafe) private let anchorProvider = PresentationAnchorProvider()
|
||||
nonisolated(unsafe) private var session: ASWebAuthenticationSession?
|
||||
private var error: Error?
|
||||
nonisolated private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "OAuthAccountAuthorizationOperation")
|
||||
|
||||
public init(accountType: AccountType) {
|
||||
self.accountType = accountType
|
||||
@@ -60,52 +74,83 @@ public final class OAuthAccountAuthorizationOperation: MainThreadOperation, @unc
|
||||
super.init(name: "OAuthAccountAuthorizationOperation")
|
||||
}
|
||||
|
||||
@MainActor public override func run() {
|
||||
public override func run() {
|
||||
Self.logger.debug("OAuthAccountAuthorizationOperation: run")
|
||||
assert(presentationAnchor != nil, "\(self) outlived presentation anchor.")
|
||||
|
||||
let request = Account.oauthAuthorizationCodeGrantRequest(for: accountType)
|
||||
|
||||
guard let url = request.url else {
|
||||
return DispatchQueue.main.async {
|
||||
self.didEndAuthentication(url: nil, error: URLError(.badURL))
|
||||
}
|
||||
didEndAuthentication(url: nil, error: URLError(.badURL))
|
||||
return
|
||||
}
|
||||
|
||||
guard let redirectUri = URL(string: oauthClient.redirectUri), let scheme = redirectUri.scheme else {
|
||||
assertionFailure("Could not get callback URL scheme from \(oauthClient.redirectUri)")
|
||||
return DispatchQueue.main.async {
|
||||
self.didEndAuthentication(url: nil, error: URLError(.badURL))
|
||||
}
|
||||
didEndAuthentication(url: nil, error: URLError(.badURL))
|
||||
return
|
||||
}
|
||||
|
||||
Task.detached {
|
||||
self.createAndRunSession(url, scheme)
|
||||
}
|
||||
}
|
||||
|
||||
public func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
|
||||
guard let anchor = presentationAnchor else {
|
||||
fatalError("\(self) has outlived presentation anchor.")
|
||||
}
|
||||
return anchor
|
||||
}
|
||||
|
||||
override public func noteDidComplete() {
|
||||
Self.logger.debug("OAuthAccountAuthorizationOperation: noteDidComplete")
|
||||
|
||||
if isCanceled {
|
||||
Self.logger.debug("OAuthAccountAuthorizationOperation: noteDidComplete — canceled")
|
||||
session?.cancel()
|
||||
}
|
||||
if let error {
|
||||
Self.logger.error("OAuthAccountAuthorizationOperation: noteDidComplete — error: \(error.localizedDescription)")
|
||||
delegate?.oauthAccountAuthorizationOperation(self, didFailWith: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension OAuthAccountAuthorizationOperation {
|
||||
nonisolated func createAndRunSession(_ url: URL, _ scheme: String) {
|
||||
// Ideally this would also be on @MainActor — but there is an odd, unexplainable concurrency crash,
|
||||
// first observeed on macOS 26, when we do that.
|
||||
// <https://github.com/Ranchero-Software/NetNewsWire/issues/4937>
|
||||
// This workaround — a nonisolated func that runs @MainActor tasks — avoids the crash.
|
||||
let session = ASWebAuthenticationSession(url: url, callbackURLScheme: scheme) { url, error in
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?.didEndAuthentication(url: url, error: error)
|
||||
Task { @MainActor in
|
||||
Self.logger.debug("OAuthAccountAuthorizationOperation: ASWebAuthenticationSession callback called")
|
||||
self.didEndAuthentication(url: url, error: error)
|
||||
}
|
||||
}
|
||||
|
||||
session.presentationContextProvider = anchorProvider
|
||||
|
||||
guard session.start() else {
|
||||
|
||||
/// Documentation does not say on why `ASWebAuthenticationSession.start` or `canStart` might return false.
|
||||
/// Perhaps it has something to do with an inter-process communication failure? No browsers installed? No browsers that support web authentication?
|
||||
struct UnableToStartASWebAuthenticationSessionError: LocalizedError {
|
||||
let errorDescription: String? = NSLocalizedString("Unable to start a web authentication session with the default web browser.",
|
||||
comment: "OAuth - error description - unable to authorize because ASWebAuthenticationSession did not start.")
|
||||
let recoverySuggestion: String? = NSLocalizedString("Check your default web browser in System Preferences or change it to Safari and try again.",
|
||||
comment: "OAuth - recovery suggestion - ensure browser selected supports web authentication.")
|
||||
Task { @MainActor in
|
||||
Self.logger.error("OAuthAccountAuthorizationOperation: run — could not start session")
|
||||
error = UnableToStartASWebAuthenticationSessionError()
|
||||
didComplete()
|
||||
}
|
||||
|
||||
error = UnableToStartASWebAuthenticationSessionError()
|
||||
didComplete()
|
||||
return
|
||||
}
|
||||
|
||||
self.session = session
|
||||
}
|
||||
|
||||
@MainActor private func didEndAuthentication(url: URL?, error: Error?) {
|
||||
func didEndAuthentication(url: URL?, error: Error?) {
|
||||
if let error {
|
||||
Self.logger.error("OAuthAccountAuthorizationOperation: didEndAuthentication url: \(url?.absoluteString ?? "") error: \(error.localizedDescription)")
|
||||
} else {
|
||||
Self.logger.debug("OAuthAccountAuthorizationOperation: didEndAuthentication url: \(url?.absoluteString ?? "")")
|
||||
}
|
||||
|
||||
guard !isCanceled else {
|
||||
didComplete()
|
||||
return
|
||||
@@ -132,14 +177,7 @@ public final class OAuthAccountAuthorizationOperation: MainThreadOperation, @unc
|
||||
}
|
||||
}
|
||||
|
||||
public func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
|
||||
guard let anchor = presentationAnchor else {
|
||||
fatalError("\(self) has outlived presentation anchor.")
|
||||
}
|
||||
return anchor
|
||||
}
|
||||
|
||||
@MainActor private func didEndRequestingAccessToken(_ result: Result<OAuthAuthorizationGrant, Error>) {
|
||||
func didEndRequestingAccessToken(_ result: Result<OAuthAuthorizationGrant, Error>) {
|
||||
guard !isCanceled else {
|
||||
didComplete()
|
||||
return
|
||||
@@ -147,14 +185,17 @@ public final class OAuthAccountAuthorizationOperation: MainThreadOperation, @unc
|
||||
|
||||
switch result {
|
||||
case .success(let tokenResponse):
|
||||
Self.logger.debug("OAuthAccountAuthorizationOperation: didEndRequestingAccessToken — success")
|
||||
saveAccount(for: tokenResponse)
|
||||
case .failure(let error):
|
||||
Self.logger.error("OAuthAccountAuthorizationOperation: didEndRequestingAccessToken — failure: \(error.localizedDescription)")
|
||||
self.error = error
|
||||
didComplete()
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor private func saveAccount(for grant: OAuthAuthorizationGrant) {
|
||||
func saveAccount(for grant: OAuthAuthorizationGrant) {
|
||||
Self.logger.debug("OAuthAccountAuthorizationOperation: saveAccount")
|
||||
guard !AccountManager.shared.duplicateServiceAccount(type: .feedly, username: grant.accessToken.username) else {
|
||||
self.error = OAuthAccountAuthorizationOperationError.duplicateAccount
|
||||
didComplete()
|
||||
@@ -179,13 +220,4 @@ public final class OAuthAccountAuthorizationOperation: MainThreadOperation, @unc
|
||||
|
||||
didComplete()
|
||||
}
|
||||
|
||||
@MainActor override public func noteDidComplete() {
|
||||
if isCanceled {
|
||||
session?.cancel()
|
||||
}
|
||||
if let error {
|
||||
delegate?.oauthAccountAuthorizationOperation(self, didFailWith: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user