diff --git a/ElementX/Sources/FlowCoordinators/LinkNewDeviceFlowCoordinator.swift b/ElementX/Sources/FlowCoordinators/LinkNewDeviceFlowCoordinator.swift index 058581d80..e24686805 100644 --- a/ElementX/Sources/FlowCoordinators/LinkNewDeviceFlowCoordinator.swift +++ b/ElementX/Sources/FlowCoordinators/LinkNewDeviceFlowCoordinator.swift @@ -56,8 +56,8 @@ class LinkNewDeviceFlowCoordinator: FlowCoordinatorProtocol { guard let self else { return } switch action { - case .linkMobileDevice(let progressPublisher): - presentQRCodeScreen(mode: .linkMobile(progressPublisher)) + case .linkMobileDevice(let operation): + presentQRCodeScreen(mode: .linkMobile(operation)) case .linkDesktopComputer: presentQRCodeScreen(mode: .linkDesktop(flowParameters.userSession.clientProxy.linkNewDeviceService())) case .verifyWithAppLockPIN(let continuation): diff --git a/ElementX/Sources/Mocks/Generated/GeneratedMocks.swift b/ElementX/Sources/Mocks/Generated/GeneratedMocks.swift index d89ac4aac..684e55d30 100644 --- a/ElementX/Sources/Mocks/Generated/GeneratedMocks.swift +++ b/ElementX/Sources/Mocks/Generated/GeneratedMocks.swift @@ -8061,14 +8061,14 @@ nonisolated class LinkNewDeviceServiceMock: LinkNewDeviceServiceProtocol, @unche } private let linkMobileDeviceReturnValueLock = NSLock() - private nonisolated(unsafe) var linkMobileDeviceUnderlyingReturnValue: LinkNewDeviceService.LinkMobileProgressPublisher! - var linkMobileDeviceReturnValue: LinkNewDeviceService.LinkMobileProgressPublisher! { + private nonisolated(unsafe) var linkMobileDeviceUnderlyingReturnValue: LinkNewDeviceService.LinkMobileOperation! + var linkMobileDeviceReturnValue: LinkNewDeviceService.LinkMobileOperation! { get { linkMobileDeviceReturnValueLock.withLock { linkMobileDeviceUnderlyingReturnValue } } set { linkMobileDeviceReturnValueLock.withLock { linkMobileDeviceUnderlyingReturnValue = newValue } } } - nonisolated(unsafe) var linkMobileDeviceClosure: (() -> LinkNewDeviceService.LinkMobileProgressPublisher)? + nonisolated(unsafe) var linkMobileDeviceClosure: (() -> LinkNewDeviceService.LinkMobileOperation)? - func linkMobileDevice() -> LinkNewDeviceService.LinkMobileProgressPublisher { + func linkMobileDevice() -> LinkNewDeviceService.LinkMobileOperation { linkMobileDeviceCallsCountLock.withLock { linkMobileDeviceUnderlyingCallsCount += 1 } if let linkMobileDeviceClosure = linkMobileDeviceClosure { return linkMobileDeviceClosure() @@ -8101,14 +8101,14 @@ nonisolated class LinkNewDeviceServiceMock: LinkNewDeviceServiceProtocol, @unche } private let linkDesktopDeviceWithReturnValueLock = NSLock() - private nonisolated(unsafe) var linkDesktopDeviceWithUnderlyingReturnValue: LinkNewDeviceService.LinkDesktopProgressPublisher! - var linkDesktopDeviceWithReturnValue: LinkNewDeviceService.LinkDesktopProgressPublisher! { + private nonisolated(unsafe) var linkDesktopDeviceWithUnderlyingReturnValue: LinkNewDeviceService.LinkDesktopOperation! + var linkDesktopDeviceWithReturnValue: LinkNewDeviceService.LinkDesktopOperation! { get { linkDesktopDeviceWithReturnValueLock.withLock { linkDesktopDeviceWithUnderlyingReturnValue } } set { linkDesktopDeviceWithReturnValueLock.withLock { linkDesktopDeviceWithUnderlyingReturnValue = newValue } } } - nonisolated(unsafe) var linkDesktopDeviceWithClosure: ((Data) -> LinkNewDeviceService.LinkDesktopProgressPublisher)? + nonisolated(unsafe) var linkDesktopDeviceWithClosure: ((Data) -> LinkNewDeviceService.LinkDesktopOperation)? - func linkDesktopDevice(with scannedQRData: Data) -> LinkNewDeviceService.LinkDesktopProgressPublisher { + func linkDesktopDevice(with scannedQRData: Data) -> LinkNewDeviceService.LinkDesktopOperation { linkDesktopDeviceWithCallsCountLock.withLock { linkDesktopDeviceWithUnderlyingCallsCount += 1 } linkDesktopDeviceWithReceivedScannedQRData = scannedQRData linkDesktopDeviceWithReceivedInvocationsLock.withLock { linkDesktopDeviceWithUnderlyingReceivedInvocations.append(scannedQRData) } @@ -10380,14 +10380,14 @@ nonisolated class QRCodeLoginServiceMock: QRCodeLoginServiceProtocol, @unchecked } private let loginWithQRCodeDataReturnValueLock = NSLock() - private nonisolated(unsafe) var loginWithQRCodeDataUnderlyingReturnValue: QRLoginProgressPublisher! - var loginWithQRCodeDataReturnValue: QRLoginProgressPublisher! { + private nonisolated(unsafe) var loginWithQRCodeDataUnderlyingReturnValue: QRLoginOperation! + var loginWithQRCodeDataReturnValue: QRLoginOperation! { get { loginWithQRCodeDataReturnValueLock.withLock { loginWithQRCodeDataUnderlyingReturnValue } } set { loginWithQRCodeDataReturnValueLock.withLock { loginWithQRCodeDataUnderlyingReturnValue = newValue } } } - nonisolated(unsafe) var loginWithQRCodeDataClosure: ((Data) -> QRLoginProgressPublisher)? + nonisolated(unsafe) var loginWithQRCodeDataClosure: ((Data) -> QRLoginOperation)? - func loginWithQRCode(data: Data) -> QRLoginProgressPublisher { + func loginWithQRCode(data: Data) -> QRLoginOperation { loginWithQRCodeDataCallsCountLock.withLock { loginWithQRCodeDataUnderlyingCallsCount += 1 } loginWithQRCodeDataReceivedData = data loginWithQRCodeDataReceivedInvocationsLock.withLock { loginWithQRCodeDataUnderlyingReceivedInvocations.append(data) } diff --git a/ElementX/Sources/Mocks/LinkNewDeviceServiceMock.swift b/ElementX/Sources/Mocks/LinkNewDeviceServiceMock.swift index 9d3aa604b..88de0e69a 100644 --- a/ElementX/Sources/Mocks/LinkNewDeviceServiceMock.swift +++ b/ElementX/Sources/Mocks/LinkNewDeviceServiceMock.swift @@ -20,14 +20,14 @@ extension LinkNewDeviceServiceMock { """ struct Configuration { - var linkMobileProgressPublisher: LinkNewDeviceService.LinkMobileProgressPublisher = .init(.starting) - var linkDesktopProgressPublisher: LinkNewDeviceService.LinkDesktopProgressPublisher = .init(.starting) + var linkMobileOperation: LinkNewDeviceService.LinkMobileOperation = .init(progressPublisher: .init(.starting)) + var linkDesktopOperation: LinkNewDeviceService.LinkDesktopOperation = .init(progressPublisher: .init(.starting)) } convenience init(_ configuration: Configuration) { self.init() - linkMobileDeviceReturnValue = configuration.linkMobileProgressPublisher - linkDesktopDeviceWithReturnValue = configuration.linkDesktopProgressPublisher + linkMobileDeviceReturnValue = configuration.linkMobileOperation + linkDesktopDeviceWithReturnValue = configuration.linkDesktopOperation } } diff --git a/ElementX/Sources/Screens/LinkNewDeviceScreen/LinkNewDeviceScreenCoordinator.swift b/ElementX/Sources/Screens/LinkNewDeviceScreen/LinkNewDeviceScreenCoordinator.swift index baac325c0..54d0609e2 100644 --- a/ElementX/Sources/Screens/LinkNewDeviceScreen/LinkNewDeviceScreenCoordinator.swift +++ b/ElementX/Sources/Screens/LinkNewDeviceScreen/LinkNewDeviceScreenCoordinator.swift @@ -9,7 +9,7 @@ import Combine import SwiftUI enum LinkNewDeviceScreenCoordinatorAction { - case linkMobileDevice(LinkNewDeviceService.LinkMobileProgressPublisher) + case linkMobileDevice(LinkNewDeviceService.LinkMobileOperation) case linkDesktopComputer case verifyWithAppLockPIN(CheckedContinuation) case dismiss @@ -44,8 +44,8 @@ final class LinkNewDeviceScreenCoordinator: CoordinatorProtocol { guard let self else { return } switch action { - case .linkMobileDevice(let progressPublisher): - actionsSubject.send(.linkMobileDevice(progressPublisher)) + case .linkMobileDevice(let operation): + actionsSubject.send(.linkMobileDevice(operation)) case .linkDesktopComputer: actionsSubject.send(.linkDesktopComputer) case .verifyWithAppLockPIN(let continuation): diff --git a/ElementX/Sources/Screens/LinkNewDeviceScreen/LinkNewDeviceScreenModels.swift b/ElementX/Sources/Screens/LinkNewDeviceScreen/LinkNewDeviceScreenModels.swift index 2e9ca0b33..c2169c30e 100644 --- a/ElementX/Sources/Screens/LinkNewDeviceScreen/LinkNewDeviceScreenModels.swift +++ b/ElementX/Sources/Screens/LinkNewDeviceScreen/LinkNewDeviceScreenModels.swift @@ -8,7 +8,7 @@ import Foundation enum LinkNewDeviceScreenViewModelAction { - case linkMobileDevice(LinkNewDeviceService.LinkMobileProgressPublisher) + case linkMobileDevice(LinkNewDeviceService.LinkMobileOperation) case linkDesktopComputer case verifyWithAppLockPIN(CheckedContinuation) case dismiss diff --git a/ElementX/Sources/Screens/LinkNewDeviceScreen/LinkNewDeviceScreenViewModel.swift b/ElementX/Sources/Screens/LinkNewDeviceScreen/LinkNewDeviceScreenViewModel.swift index e1eeffae8..82e3e5f7e 100644 --- a/ElementX/Sources/Screens/LinkNewDeviceScreen/LinkNewDeviceScreenViewModel.swift +++ b/ElementX/Sources/Screens/LinkNewDeviceScreen/LinkNewDeviceScreenViewModel.swift @@ -106,17 +106,17 @@ class LinkNewDeviceScreenViewModel: LinkNewDeviceScreenViewModelType, LinkNewDev let linkNewDeviceService = clientProxy.linkNewDeviceService() - let progressPublisher = linkNewDeviceService.linkMobileDevice() + let linkMobileOperation = linkNewDeviceService.linkMobileDevice() do { - var iterator = progressPublisher.values.makeAsyncIterator() + var iterator = linkMobileOperation.progressPublisher.values.makeAsyncIterator() while let progress = try await iterator.next(isolation: #isolation) { if case .qrReady = progress { break } } - actionsSubject.send(.linkMobileDevice(progressPublisher)) + actionsSubject.send(.linkMobileDevice(linkMobileOperation)) state.mode = .readyToLink(.idle) } catch { // This is hard to share a mapping from the QRCodeLoginError with the diff --git a/ElementX/Sources/Screens/QRCodeLoginScreen/QRCodeLoginScreenModels.swift b/ElementX/Sources/Screens/QRCodeLoginScreen/QRCodeLoginScreenModels.swift index 4cb24c325..a5cd592d9 100644 --- a/ElementX/Sources/Screens/QRCodeLoginScreen/QRCodeLoginScreenModels.swift +++ b/ElementX/Sources/Screens/QRCodeLoginScreen/QRCodeLoginScreenModels.swift @@ -39,7 +39,7 @@ enum QRCodeLoginScreenMode { /// Configures the screen to link another device by scanning a QR code. case linkDesktop(LinkNewDeviceServiceProtocol) /// Configures the screen to link another device by showing it a QR code. - case linkMobile(LinkNewDeviceService.LinkMobileProgressPublisher) + case linkMobile(LinkNewDeviceService.LinkMobileOperation) } struct QRCodeLoginScreenViewState: BindableState { diff --git a/ElementX/Sources/Screens/QRCodeLoginScreen/QRCodeLoginScreenViewModel.swift b/ElementX/Sources/Screens/QRCodeLoginScreen/QRCodeLoginScreenViewModel.swift index 66e2efe20..7f3fd57b6 100644 --- a/ElementX/Sources/Screens/QRCodeLoginScreen/QRCodeLoginScreenViewModel.swift +++ b/ElementX/Sources/Screens/QRCodeLoginScreen/QRCodeLoginScreenViewModel.swift @@ -24,7 +24,7 @@ class QRCodeLoginScreenViewModel: QRCodeLoginScreenViewModelType, QRCodeLoginScr actionsSubject.eraseToAnyPublisher() } - private var currentTask: AnyCancellable? + private var currentOperation: CurrentOperation? private var oAuthResultTask: AnyCancellable? private var expirationTask: AnyCancellable? @@ -38,8 +38,8 @@ class QRCodeLoginScreenViewModel: QRCodeLoginScreenViewModelType, QRCodeLoginScr let initialViewState: QRCodeLoginState = switch mode { case .login: .loginInstructions case .linkDesktop: .linkDesktopInstructions - case .linkMobile(let progressPublisher): - switch progressPublisher.value { + case .linkMobile(let operation): + switch operation.progressPublisher.value { case .qrReady(let image): .displayQR(image) default: .error(.unknown) } @@ -51,8 +51,8 @@ class QRCodeLoginScreenViewModel: QRCodeLoginScreenViewModelType, QRCodeLoginScr switch mode { case .linkDesktop: scheduleLinkDesktopExpiration() - case .linkMobile(let progressPublisher): - listenToDisplayQRProgress(progressPublisher: progressPublisher) + case .linkMobile(let operation): + listenToDisplayQRProgress(operation: operation) case .login: break } @@ -62,7 +62,10 @@ class QRCodeLoginScreenViewModel: QRCodeLoginScreenViewModelType, QRCodeLoginScr override func process(viewAction: QRCodeLoginScreenViewAction) { switch viewAction { - case .cancel, .errorAction(.cancel): + case .cancel: + currentOperation?.closeRendezvousChannel() + actionsSubject.send(.cancel) + case .errorAction(.cancel): actionsSubject.send(.cancel) case .startScan: Task { await startScanIfPossible() } @@ -116,19 +119,19 @@ class QRCodeLoginScreenViewModel: QRCodeLoginScreenViewModelType, QRCodeLoginScr } private func handleScan(qrData: Data, loginService: QRCodeLoginServiceProtocol) { - guard currentTask == nil else { return } + guard currentOperation == nil else { return } state.state = .scan(.connecting) MXLog.info("Login scanning QR code") - let progressPublisher = loginService.loginWithQRCode(data: qrData) + let operation = loginService.loginWithQRCode(data: qrData) - currentTask = progressPublisher + let progressCancellable = operation.progressPublisher .removeDuplicates() .receive(on: DispatchQueue.main) .sink { [weak self] completion in guard let self else { return } - currentTask = nil + currentOperation = nil switch completion { case .finished: break @@ -160,22 +163,24 @@ class QRCodeLoginScreenViewModel: QRCodeLoginScreenViewModelType, QRCodeLoginScr actionsSubject.send(.signedIn(userSession: session)) } } + + currentOperation = .init(progressCancellable: progressCancellable, closeRendezvousChannelAction: operation.closeRendezvousChannel) } private func handleScan(qrData: Data, linkService: LinkNewDeviceServiceProtocol) { - guard currentTask == nil else { return } + guard currentOperation == nil else { return } state.state = .scan(.connecting) MXLog.info("Link scanning QR code") - let progressPublisher = linkService.linkDesktopDevice(with: qrData) + let operation = linkService.linkDesktopDevice(with: qrData) - currentTask = progressPublisher + let progressCancellable = operation.progressPublisher .removeDuplicates() .receive(on: DispatchQueue.main) .sink { [weak self] completion in guard let self else { return } - currentTask = nil + currentOperation = nil if case .failure(let error) = completion { handleError(error) @@ -204,19 +209,21 @@ class QRCodeLoginScreenViewModel: QRCodeLoginScreenViewModelType, QRCodeLoginScr actionsSubject.send(.linkedDevice) } } + + currentOperation = .init(progressCancellable: progressCancellable, closeRendezvousChannelAction: operation.closeRendezvousChannel) } - private func listenToDisplayQRProgress(progressPublisher: LinkNewDeviceService.LinkMobileProgressPublisher) { + private func listenToDisplayQRProgress(operation: LinkNewDeviceService.LinkMobileOperation) { state.bindings.qrResult = nil MXLog.info("Link showing QR code.") - currentTask = progressPublisher + let progressCancellable = operation.progressPublisher .removeDuplicates() .receive(on: DispatchQueue.main) .sink { [weak self] completion in guard let self else { return } - currentTask = nil + currentOperation = nil if case .failure(let error) = completion { handleError(error) @@ -244,9 +251,11 @@ class QRCodeLoginScreenViewModel: QRCodeLoginScreenViewModelType, QRCodeLoginScr actionsSubject.send(.linkedDevice) } } + + currentOperation = .init(progressCancellable: progressCancellable, closeRendezvousChannelAction: operation.closeRendezvousChannel) } - /// Starts the timeout for scanning a desktop's QR code. The flow will expire (cancelling the scan) + /// Starts the timeout for scanning a desktop's QR code. The flow will expire (closing the rendezvous channel) /// if the secure channel isn't established within the timeout period. private func scheduleLinkDesktopExpiration() { guard case .linkDesktop = state.mode else { fatalError("Expiration requested on an unexpected flow") } @@ -262,12 +271,13 @@ class QRCodeLoginScreenViewModel: QRCodeLoginScreenViewModelType, QRCodeLoginScr private func handleExpiration() { // Don't override an error that's already being shown. if case .error = state.state { - currentTask = nil // Cancel the scan (just in case). + currentOperation = nil // Stop listening for updates (just in case). return } MXLog.info("Timed out establishing a secure channel, expiring.") - currentTask = nil // Cancel the scan. + currentOperation?.closeRendezvousChannel() + currentOperation = nil // Stop listening for updates. handleError(.expired) } @@ -356,6 +366,21 @@ class QRCodeLoginScreenViewModel: QRCodeLoginScreenViewModelType, QRCodeLoginScr } } +/// The screen's currently running operation. This includes a subscription to its progress and a way to close +/// its rendezvous channel early. Releasing it only stops listening to the progress. The rendezvous channel +/// can be closed mid-operation by calling ``closeRendezvousChannel()``. +private struct CurrentOperation { + let progressCancellable: AnyCancellable + let closeRendezvousChannelAction: () -> Void + + /// Closes the operation's rendezvous channel and stops listening to its progress. + func closeRendezvousChannel() { + // Must come first so the resulting `.cancelled` failure isn't handled. + progressCancellable.cancel() + closeRendezvousChannelAction() + } +} + extension QRCodeLoginScreenViewModel { static func mock(state: QRCodeLoginState, mode: QRCodeLoginScreenMode = .login(QRCodeLoginServiceMock()), diff --git a/ElementX/Sources/Services/Authentication/AuthenticationService.swift b/ElementX/Sources/Services/Authentication/AuthenticationService.swift index db7850682..c11fbfd9b 100644 --- a/ElementX/Sources/Services/Authentication/AuthenticationService.swift +++ b/ElementX/Sources/Services/Authentication/AuthenticationService.swift @@ -181,7 +181,7 @@ class AuthenticationService: AuthenticationServiceProtocol { } } - func loginWithQRCode(data: Data) -> QRLoginProgressPublisher { + func loginWithQRCode(data: Data) -> QRLoginOperation { let progressSubject = CurrentValueSubject(.starting) let qrData: QrCodeData @@ -190,7 +190,7 @@ class AuthenticationService: AuthenticationServiceProtocol { } catch { MXLog.error("QRCode decode error: \(error)") progressSubject.send(completion: .failure(.qrCodeError(.invalidQRCode))) - return progressSubject.asCurrentValuePublisher() + return QRLoginOperation(progressPublisher: progressSubject.asCurrentValuePublisher()) } // n.b. We rely on the SDK checking that the intent of the QR is suitable for us to login with. @@ -201,7 +201,7 @@ class AuthenticationService: AuthenticationServiceProtocol { // is not signed in. MXLog.error("The QR code is from a device that is not yet signed in.") progressSubject.send(completion: .failure(.qrCodeError(.deviceNotSignedIn))) - return progressSubject.asCurrentValuePublisher() + return QRLoginOperation(progressPublisher: progressSubject.asCurrentValuePublisher()) } // When account provider selection is restricted, make sure the scanned server is allowed. @@ -215,7 +215,7 @@ class AuthenticationService: AuthenticationServiceProtocol { let error = QRCodeLoginError.providerNotAllowed(scannedProvider: scannedServerNameOrBaseURL, allowedProviders: appSettings.accountProviders.map(\.serverNameOrBaseURL)) progressSubject.send(completion: .failure(.qrCodeError(error))) - return progressSubject.asCurrentValuePublisher() + return QRLoginOperation(progressPublisher: progressSubject.asCurrentValuePublisher()) } } @@ -226,11 +226,12 @@ class AuthenticationService: AuthenticationServiceProtocol { progressSubject.send(progress) } - Task { + let task = Task { do { let client = try await makeClient(serverNameOrBaseURL: scannedServerNameOrBaseURL) let qrCodeHandler = client.newLoginWithQrCodeHandler(oauthConfiguration: appSettings.oAuthConfiguration.rustValue) - try await qrCodeHandler.scan(qrCodeData: qrData, progressListener: listener).wait() + let sdkTask = try qrCodeHandler.scan(qrCodeData: qrData, progressListener: listener) + try await withTaskCancellationHandler(operation: sdkTask.wait, onCancel: sdkTask.cancel) switch await userSession(for: client) { case .success(let userSession): @@ -251,7 +252,7 @@ class AuthenticationService: AuthenticationServiceProtocol { } } - return progressSubject.asCurrentValuePublisher() + return QRLoginOperation(progressPublisher: progressSubject.asCurrentValuePublisher(), task: task) } func reset() { diff --git a/ElementX/Sources/Services/Authentication/AuthenticationServiceProtocol.swift b/ElementX/Sources/Services/Authentication/AuthenticationServiceProtocol.swift index 13669d4d3..422974078 100644 --- a/ElementX/Sources/Services/Authentication/AuthenticationServiceProtocol.swift +++ b/ElementX/Sources/Services/Authentication/AuthenticationServiceProtocol.swift @@ -127,8 +127,25 @@ enum QRCodeLoginError: Error, Equatable { // sourcery: AutoMockable protocol QRCodeLoginServiceProtocol { - typealias QRLoginProgressPublisher = CurrentValuePublisher - func loginWithQRCode(data: Data) -> QRLoginProgressPublisher + /// A ``QRCodeOperation`` for logging in by scanning a QR code generated by another device. + typealias QRLoginOperation = QRCodeOperation + func loginWithQRCode(data: Data) -> QRLoginOperation +} + +/// An ongoing QR code login or link operation that publishes its progress with to ability to close the rendezvous channel early. +final class QRCodeOperation { + let progressPublisher: CurrentValuePublisher + private let task: Task? + + init(progressPublisher: CurrentValuePublisher, task: Task? = nil) { + self.progressPublisher = progressPublisher + self.task = task + } + + /// Closes the operation's rendezvous channel. The publisher will then fail with its cancelled error. + func closeRendezvousChannel() { + task?.cancel() + } } enum QRLoginProgress { diff --git a/ElementX/Sources/Services/Authentication/LinkNewDeviceService.swift b/ElementX/Sources/Services/Authentication/LinkNewDeviceService.swift index c061297c7..f64f52b78 100644 --- a/ElementX/Sources/Services/Authentication/LinkNewDeviceService.swift +++ b/ElementX/Sources/Services/Authentication/LinkNewDeviceService.swift @@ -13,16 +13,16 @@ import SwiftUI // sourcery: AutoMockable protocol LinkNewDeviceServiceProtocol { /// Links a new device by showing it a QR code. - func linkMobileDevice() -> LinkNewDeviceService.LinkMobileProgressPublisher + func linkMobileDevice() -> LinkNewDeviceService.LinkMobileOperation /// Links a new device using a QR code generated by said device. - func linkDesktopDevice(with scannedQRData: Data) -> LinkNewDeviceService.LinkDesktopProgressPublisher + func linkDesktopDevice(with scannedQRData: Data) -> LinkNewDeviceService.LinkDesktopOperation } class LinkNewDeviceService: LinkNewDeviceServiceProtocol { - /// Publishes the progress of linking a new device by showing it a QR code. - typealias LinkMobileProgressPublisher = CurrentValuePublisher - /// Publishes the progress of linking a new device by scanning a QR code generated by said device. - typealias LinkDesktopProgressPublisher = CurrentValuePublisher + /// A ``QRCodeOperation`` for linking a new device by showing it a QR code. + typealias LinkMobileOperation = QRCodeOperation + /// A ``QRCodeOperation`` for linking a new device by scanning a QR code generated by said device. + typealias LinkDesktopOperation = QRCodeOperation /// The progress of linking a new device by showing it a QR code. enum LinkMobileProgress: Equatable { @@ -50,7 +50,7 @@ class LinkNewDeviceService: LinkNewDeviceServiceProtocol { } /// Links a new device by showing it a QR code. - func linkMobileDevice() -> LinkMobileProgressPublisher { + func linkMobileDevice() -> LinkMobileOperation { let progressSubject = CurrentValueSubject(.starting) // Bridge from the SDK's synchronous callback into Swift Concurrency. Yielding is safe from @@ -73,11 +73,12 @@ class LinkNewDeviceService: LinkNewDeviceServiceProtocol { } } - Task { + let task = Task { defer { progressContinuation.finish() } do { - // Note: The SDK doesn't provide us with a way to cancel the grant if the user hit the cancel button 🤷‍♂️ - try await grantLoginHandler.generate(progressListener: listener).wait() // The success state is handled by the listener. + let sdkTask = try grantLoginHandler.generate(progressListener: listener) + try await withTaskCancellationHandler(operation: sdkTask.wait, onCancel: sdkTask.cancel) + // We send the .done progress in case the listener didn't get a chance to pass it on from the SDK before being deallocated progressSubject.send(LinkMobileProgress.done) } catch let error as HumanQrGrantLoginError { @@ -89,11 +90,11 @@ class LinkNewDeviceService: LinkNewDeviceServiceProtocol { } } - return progressSubject.asCurrentValuePublisher() + return LinkMobileOperation(progressPublisher: progressSubject.asCurrentValuePublisher(), task: task) } /// Links a new device using a QR code generated by said device. - func linkDesktopDevice(with scannedQRData: Data) -> LinkDesktopProgressPublisher { + func linkDesktopDevice(with scannedQRData: Data) -> LinkDesktopOperation { let progressSubject = CurrentValueSubject(.starting) // Same callback bridging as `linkMobileDevice()` above. @@ -121,17 +122,18 @@ class LinkNewDeviceService: LinkNewDeviceServiceProtocol { MXLog.error("QR code decode error: \(error)") progressSubject.send(completion: .failure(.invalidQRCode)) progressContinuation.finish() - return progressSubject.asCurrentValuePublisher() + return LinkDesktopOperation(progressPublisher: progressSubject.asCurrentValuePublisher()) } // At some stage the SDK will have a `qrCodeData.intent` which we should check before continuing here. // Note the equivalent check will also happen for sign in with QR code in the AuthenticationService. - Task { + let task = Task { defer { progressContinuation.finish() } do { - // Note: The SDK doesn't provide us with a way to cancel the grant if the user hit the cancel button 🤷‍♂️ - try await grantLoginHandler.scan(qrCodeData: qrCodeData, progressListener: listener).wait() // The success state is handled by the listener. + let sdkTask = try grantLoginHandler.scan(qrCodeData: qrCodeData, progressListener: listener) + try await withTaskCancellationHandler(operation: sdkTask.wait, onCancel: sdkTask.cancel) + // We send the .done progress in case the listener didn't get a chance to pass it on from the SDK before being deallocated progressSubject.send(LinkDesktopProgress.done) } catch let error as HumanQrGrantLoginError { @@ -143,7 +145,7 @@ class LinkNewDeviceService: LinkNewDeviceServiceProtocol { } } - return progressSubject.asCurrentValuePublisher() + return LinkDesktopOperation(progressPublisher: progressSubject.asCurrentValuePublisher(), task: task) } } diff --git a/ElementX/Sources/UITests/UITestsAppCoordinator.swift b/ElementX/Sources/UITests/UITestsAppCoordinator.swift index d5ca3f49b..1cf7dc12a 100644 --- a/ElementX/Sources/UITests/UITestsAppCoordinator.swift +++ b/ElementX/Sources/UITests/UITestsAppCoordinator.swift @@ -751,7 +751,7 @@ class MockScreen: Identifiable { return navigationStackCoordinator case .linkNewDevice, .linkNewDeviceWithAppLockPIN: let linkMobileProgressSubject: CurrentValueSubject = .init(.qrReady(LinkNewDeviceServiceMock.mockQRCodeImage)) - let linkNewDeviceService = LinkNewDeviceServiceMock(.init(linkMobileProgressPublisher: linkMobileProgressSubject.asCurrentValuePublisher())) + let linkNewDeviceService = LinkNewDeviceServiceMock(.init(linkMobileOperation: .init(progressPublisher: linkMobileProgressSubject.asCurrentValuePublisher()))) let clientProxy = ClientProxyMock(.init()) clientProxy.linkNewDeviceServiceReturnValue = linkNewDeviceService diff --git a/UnitTests/Sources/LinkNewDeviceScreenViewModelTests.swift b/UnitTests/Sources/LinkNewDeviceScreenViewModelTests.swift index c87a400c2..b51848011 100644 --- a/UnitTests/Sources/LinkNewDeviceScreenViewModelTests.swift +++ b/UnitTests/Sources/LinkNewDeviceScreenViewModelTests.swift @@ -48,7 +48,7 @@ class LinkNewDeviceScreenViewModelTests { func linkingMobileDeviceVerifiesThenGeneratesQRCode() async throws { // Given a ready screen whose QR code isn't immediately available. let progressSubject = CurrentValueSubject(.starting) - setupViewModel(linkMobileProgressPublisher: progressSubject.asCurrentValuePublisher(), + setupViewModel(linkMobileOperation: .init(progressPublisher: progressSubject.asCurrentValuePublisher()), mode: .loading) // When linking a mobile device. @@ -94,7 +94,7 @@ class LinkNewDeviceScreenViewModelTests { func linkingWithoutDevicePasscodeOrAppLockPIN() async throws { // Given a device with neither a passcode nor an App Lock PIN set (device owner verification is unavailable). let progressSubject = CurrentValueSubject(.starting) - setupViewModel(linkMobileProgressPublisher: progressSubject.asCurrentValuePublisher(), + setupViewModel(linkMobileOperation: .init(progressPublisher: progressSubject.asCurrentValuePublisher()), deviceOwnerResult: .unavailable, mode: .loading) @@ -140,7 +140,7 @@ class LinkNewDeviceScreenViewModelTests { func appLockPINVerifiedContinuesLinking() async throws { // Given a device that requires App Lock PIN verification. let progressSubject = CurrentValueSubject(.starting) - setupViewModel(linkMobileProgressPublisher: progressSubject.asCurrentValuePublisher(), + setupViewModel(linkMobileOperation: .init(progressPublisher: progressSubject.asCurrentValuePublisher()), deviceOwnerResult: .appLockPINRequired, mode: .loading) @@ -254,13 +254,13 @@ class LinkNewDeviceScreenViewModelTests { // MARK: - Helpers private func setupViewModel(isLoginWithQRCodeSupported: Bool = true, - linkMobileProgressPublisher: LinkNewDeviceService.LinkMobileProgressPublisher = .init(.qrReady(LinkNewDeviceServiceMock.mockQRCodeImage)), + linkMobileOperation: LinkNewDeviceService.LinkMobileOperation = .init(progressPublisher: .init(.qrReady(LinkNewDeviceServiceMock.mockQRCodeImage))), deviceOwnerResult: AppLockDeviceOwnerResult = .verified, mode: LinkNewDeviceScreenViewState.Mode? = nil) { let clientProxy = ClientProxyMock(.init()) clientProxy.underlyingIsLoginWithQRCodeSupported = isLoginWithQRCodeSupported - linkNewDeviceService = LinkNewDeviceServiceMock(.init(linkMobileProgressPublisher: linkMobileProgressPublisher)) + linkNewDeviceService = LinkNewDeviceServiceMock(.init(linkMobileOperation: linkMobileOperation)) clientProxy.linkNewDeviceServiceReturnValue = linkNewDeviceService appLockService = AppLockServiceMock.mock() diff --git a/UnitTests/Sources/QRCodeLoginScreenViewModelTests.swift b/UnitTests/Sources/QRCodeLoginScreenViewModelTests.swift index db0653d75..7f584311e 100644 --- a/UnitTests/Sources/QRCodeLoginScreenViewModelTests.swift +++ b/UnitTests/Sources/QRCodeLoginScreenViewModelTests.swift @@ -223,17 +223,129 @@ struct QRCodeLoginScreenViewModelTests { try await deferredAction.fulfill() } + // MARK: - Cancellation + + @Test + mutating func cancelLoginClosesRendezvousChannel() async throws { + // Given a screen that has scanned a QR code to log in. + let operationTask = Task { _ = try? await Task.sleep(for: .seconds(3600)) } + setup(mode: .login, operationTask: operationTask) + try await scanQRCode() + + // When cancelling. + let deferredAction = deferFulfillment(viewModel.actionsPublisher) { $0.isCancel } + context.send(viewAction: .cancel) + try await deferredAction.fulfill() + + // Then the login's rendezvous channel should be closed. + #expect(operationTask.isCancelled) + } + + @Test + mutating func cancelLinkDesktopClosesRendezvousChannel() async throws { + // Given a screen that has scanned a desktop's QR code. + let operationTask = Task { _ = try? await Task.sleep(for: .seconds(3600)) } + setup(mode: .linkDesktop, operationTask: operationTask) + try await scanQRCode() + + // When cancelling. + let deferredAction = deferFulfillment(viewModel.actionsPublisher) { $0.isCancel } + context.send(viewAction: .cancel) + try await deferredAction.fulfill() + + // Then the link's rendezvous channel should be closed. + #expect(operationTask.isCancelled) + } + + @Test + mutating func cancelLinkMobileClosesRendezvousChannel() async throws { + // Given a screen showing a QR code for a mobile device to scan. + let operationTask = Task { _ = try? await Task.sleep(for: .seconds(3600)) } + setup(mode: .linkMobile, operationTask: operationTask) + #expect(context.viewState.state.isDisplayQR) + + // When cancelling. + let deferredAction = deferFulfillment(viewModel.actionsPublisher) { $0.isCancel } + context.send(viewAction: .cancel) + try await deferredAction.fulfill() + + // Then the link's rendezvous channel should be closed. + #expect(operationTask.isCancelled) + } + + @Test + mutating func linkDesktopExpiryClosesRendezvousChannel() async throws { + // Given a screen linking a desktop with a short timeout. + let operationTask = Task { _ = try? await Task.sleep(for: .seconds(3600)) } + setup(mode: .linkDesktop, linkDesktopTimeout: .seconds(1), operationTask: operationTask) + + // When the timeout passes after scanning but before a secure channel is established. + let deferredExpiry = deferFulfillment(context.$viewState) { $0.state == .error(.expired) } + try await scanQRCode() + try await deferredExpiry.fulfill() + + // Then the link's rendezvous channel should be closed. + #expect(operationTask.isCancelled) + } + + @Test + mutating func linkDesktopExpiryIsNotReplacedByLaterError() async throws { + // Given a screen whose link has expired after scanning. + setup(mode: .linkDesktop, linkDesktopTimeout: .seconds(1)) + + let deferredExpiry = deferFulfillment(context.$viewState) { $0.state == .error(.expired) } + try await scanQRCode() + try await deferredExpiry.fulfill() + + // When Rust later reports an error for the cancelled link. + let deferredFailure = deferFailure(context.$viewState, timeout: .seconds(1)) { $0.state != .error(.expired) } + linkDesktopProgressSubject.send(completion: .failure(.cancelled)) + + // Then the expired error should still be shown. + try await deferredFailure.fulfill() + } + + @Test + mutating func cancelFromErrorDoesNotCloseRendezvousChannel() async throws { + // Given a screen showing an error because the Rust SDK's link has failed. + let operationTask = Task { _ = try? await Task.sleep(for: .seconds(3600)) } + setup(mode: .linkDesktop, operationTask: operationTask) + try await scanQRCode() + + let deferredError = deferFulfillment(context.$viewState) { $0.state == .error(.connectionNotSecure) } + linkDesktopProgressSubject.send(completion: .failure(.connectionInsecure)) + try await deferredError.fulfill() + + // When cancelling from the error. + let deferredAction = deferFulfillment(viewModel.actionsPublisher) { $0.isCancel } + context.send(viewAction: .errorAction(.cancel)) + try await deferredAction.fulfill() + + // Then the flow should be dismissed without trying to close the finished rendezvous channel. + #expect(!operationTask.isCancelled) + } + // MARK: - Helpers - private mutating func setup(mode: Mode, linkDesktopTimeout: Duration = .seconds(120)) { + private func scanQRCode() async throws { + var deferred = deferFulfillment(context.$viewState) { $0.state == .scan(.scanning) } + context.send(viewAction: .startScan) + try await deferred.fulfill() + + deferred = deferFulfillment(context.$viewState) { $0.state == .scan(.connecting) } + context.qrResult = .init() + try await deferred.fulfill() + } + + private mutating func setup(mode: Mode, linkDesktopTimeout: Duration = .seconds(120), operationTask: Task? = nil) { qrLoginProgressSubject = .init(.starting) qrCodeLoginService = QRCodeLoginServiceMock() - qrCodeLoginService.loginWithQRCodeDataReturnValue = qrLoginProgressSubject.asCurrentValuePublisher() + qrCodeLoginService.loginWithQRCodeDataReturnValue = .init(progressPublisher: qrLoginProgressSubject.asCurrentValuePublisher(), task: operationTask) linkMobileProgressSubject = .init(.qrReady(LinkNewDeviceServiceMock.mockQRCodeImage)) linkDesktopProgressSubject = .init(.starting) - linkNewDeviceService = LinkNewDeviceServiceMock(.init(linkMobileProgressPublisher: linkMobileProgressSubject.asCurrentValuePublisher(), - linkDesktopProgressPublisher: linkDesktopProgressSubject.asCurrentValuePublisher())) + linkNewDeviceService = LinkNewDeviceServiceMock(.init(linkMobileOperation: .init(progressPublisher: linkMobileProgressSubject.asCurrentValuePublisher(), task: operationTask), + linkDesktopOperation: .init(progressPublisher: linkDesktopProgressSubject.asCurrentValuePublisher(), task: operationTask))) let screenMode: QRCodeLoginScreenMode switch mode { @@ -252,3 +364,12 @@ struct QRCodeLoginScreenViewModelTests { linkDesktopTimeout: linkDesktopTimeout) } } + +private extension QRCodeLoginScreenViewModelAction { + var isCancel: Bool { + switch self { + case .cancel: true + default: false + } + } +}