mirror of
https://github.com/Novaloop-AG/element-x-ios.git
synced 2026-11-27 12:08:50 +00:00
Add support for QR code task cancellation. (#6373)
* Add support for cancelling QR code operations. * Send QR code screen cancellations back to the SDK. * Add tests for cancellation.
This commit is contained in:
@@ -56,8 +56,8 @@ class LinkNewDeviceFlowCoordinator: FlowCoordinatorProtocol {
|
|||||||
guard let self else { return }
|
guard let self else { return }
|
||||||
|
|
||||||
switch action {
|
switch action {
|
||||||
case .linkMobileDevice(let progressPublisher):
|
case .linkMobileDevice(let operation):
|
||||||
presentQRCodeScreen(mode: .linkMobile(progressPublisher))
|
presentQRCodeScreen(mode: .linkMobile(operation))
|
||||||
case .linkDesktopComputer:
|
case .linkDesktopComputer:
|
||||||
presentQRCodeScreen(mode: .linkDesktop(flowParameters.userSession.clientProxy.linkNewDeviceService()))
|
presentQRCodeScreen(mode: .linkDesktop(flowParameters.userSession.clientProxy.linkNewDeviceService()))
|
||||||
case .verifyWithAppLockPIN(let continuation):
|
case .verifyWithAppLockPIN(let continuation):
|
||||||
|
|||||||
@@ -8061,14 +8061,14 @@ nonisolated class LinkNewDeviceServiceMock: LinkNewDeviceServiceProtocol, @unche
|
|||||||
}
|
}
|
||||||
|
|
||||||
private let linkMobileDeviceReturnValueLock = NSLock()
|
private let linkMobileDeviceReturnValueLock = NSLock()
|
||||||
private nonisolated(unsafe) var linkMobileDeviceUnderlyingReturnValue: LinkNewDeviceService.LinkMobileProgressPublisher!
|
private nonisolated(unsafe) var linkMobileDeviceUnderlyingReturnValue: LinkNewDeviceService.LinkMobileOperation!
|
||||||
var linkMobileDeviceReturnValue: LinkNewDeviceService.LinkMobileProgressPublisher! {
|
var linkMobileDeviceReturnValue: LinkNewDeviceService.LinkMobileOperation! {
|
||||||
get { linkMobileDeviceReturnValueLock.withLock { linkMobileDeviceUnderlyingReturnValue } }
|
get { linkMobileDeviceReturnValueLock.withLock { linkMobileDeviceUnderlyingReturnValue } }
|
||||||
set { linkMobileDeviceReturnValueLock.withLock { linkMobileDeviceUnderlyingReturnValue = newValue } }
|
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 }
|
linkMobileDeviceCallsCountLock.withLock { linkMobileDeviceUnderlyingCallsCount += 1 }
|
||||||
if let linkMobileDeviceClosure = linkMobileDeviceClosure {
|
if let linkMobileDeviceClosure = linkMobileDeviceClosure {
|
||||||
return linkMobileDeviceClosure()
|
return linkMobileDeviceClosure()
|
||||||
@@ -8101,14 +8101,14 @@ nonisolated class LinkNewDeviceServiceMock: LinkNewDeviceServiceProtocol, @unche
|
|||||||
}
|
}
|
||||||
|
|
||||||
private let linkDesktopDeviceWithReturnValueLock = NSLock()
|
private let linkDesktopDeviceWithReturnValueLock = NSLock()
|
||||||
private nonisolated(unsafe) var linkDesktopDeviceWithUnderlyingReturnValue: LinkNewDeviceService.LinkDesktopProgressPublisher!
|
private nonisolated(unsafe) var linkDesktopDeviceWithUnderlyingReturnValue: LinkNewDeviceService.LinkDesktopOperation!
|
||||||
var linkDesktopDeviceWithReturnValue: LinkNewDeviceService.LinkDesktopProgressPublisher! {
|
var linkDesktopDeviceWithReturnValue: LinkNewDeviceService.LinkDesktopOperation! {
|
||||||
get { linkDesktopDeviceWithReturnValueLock.withLock { linkDesktopDeviceWithUnderlyingReturnValue } }
|
get { linkDesktopDeviceWithReturnValueLock.withLock { linkDesktopDeviceWithUnderlyingReturnValue } }
|
||||||
set { linkDesktopDeviceWithReturnValueLock.withLock { linkDesktopDeviceWithUnderlyingReturnValue = newValue } }
|
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 }
|
linkDesktopDeviceWithCallsCountLock.withLock { linkDesktopDeviceWithUnderlyingCallsCount += 1 }
|
||||||
linkDesktopDeviceWithReceivedScannedQRData = scannedQRData
|
linkDesktopDeviceWithReceivedScannedQRData = scannedQRData
|
||||||
linkDesktopDeviceWithReceivedInvocationsLock.withLock { linkDesktopDeviceWithUnderlyingReceivedInvocations.append(scannedQRData) }
|
linkDesktopDeviceWithReceivedInvocationsLock.withLock { linkDesktopDeviceWithUnderlyingReceivedInvocations.append(scannedQRData) }
|
||||||
@@ -10380,14 +10380,14 @@ nonisolated class QRCodeLoginServiceMock: QRCodeLoginServiceProtocol, @unchecked
|
|||||||
}
|
}
|
||||||
|
|
||||||
private let loginWithQRCodeDataReturnValueLock = NSLock()
|
private let loginWithQRCodeDataReturnValueLock = NSLock()
|
||||||
private nonisolated(unsafe) var loginWithQRCodeDataUnderlyingReturnValue: QRLoginProgressPublisher!
|
private nonisolated(unsafe) var loginWithQRCodeDataUnderlyingReturnValue: QRLoginOperation!
|
||||||
var loginWithQRCodeDataReturnValue: QRLoginProgressPublisher! {
|
var loginWithQRCodeDataReturnValue: QRLoginOperation! {
|
||||||
get { loginWithQRCodeDataReturnValueLock.withLock { loginWithQRCodeDataUnderlyingReturnValue } }
|
get { loginWithQRCodeDataReturnValueLock.withLock { loginWithQRCodeDataUnderlyingReturnValue } }
|
||||||
set { loginWithQRCodeDataReturnValueLock.withLock { loginWithQRCodeDataUnderlyingReturnValue = newValue } }
|
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 }
|
loginWithQRCodeDataCallsCountLock.withLock { loginWithQRCodeDataUnderlyingCallsCount += 1 }
|
||||||
loginWithQRCodeDataReceivedData = data
|
loginWithQRCodeDataReceivedData = data
|
||||||
loginWithQRCodeDataReceivedInvocationsLock.withLock { loginWithQRCodeDataUnderlyingReceivedInvocations.append(data) }
|
loginWithQRCodeDataReceivedInvocationsLock.withLock { loginWithQRCodeDataUnderlyingReceivedInvocations.append(data) }
|
||||||
|
|||||||
@@ -20,14 +20,14 @@ extension LinkNewDeviceServiceMock {
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
struct Configuration {
|
struct Configuration {
|
||||||
var linkMobileProgressPublisher: LinkNewDeviceService.LinkMobileProgressPublisher = .init(.starting)
|
var linkMobileOperation: LinkNewDeviceService.LinkMobileOperation = .init(progressPublisher: .init(.starting))
|
||||||
var linkDesktopProgressPublisher: LinkNewDeviceService.LinkDesktopProgressPublisher = .init(.starting)
|
var linkDesktopOperation: LinkNewDeviceService.LinkDesktopOperation = .init(progressPublisher: .init(.starting))
|
||||||
}
|
}
|
||||||
|
|
||||||
convenience init(_ configuration: Configuration) {
|
convenience init(_ configuration: Configuration) {
|
||||||
self.init()
|
self.init()
|
||||||
|
|
||||||
linkMobileDeviceReturnValue = configuration.linkMobileProgressPublisher
|
linkMobileDeviceReturnValue = configuration.linkMobileOperation
|
||||||
linkDesktopDeviceWithReturnValue = configuration.linkDesktopProgressPublisher
|
linkDesktopDeviceWithReturnValue = configuration.linkDesktopOperation
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import Combine
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
|
||||||
enum LinkNewDeviceScreenCoordinatorAction {
|
enum LinkNewDeviceScreenCoordinatorAction {
|
||||||
case linkMobileDevice(LinkNewDeviceService.LinkMobileProgressPublisher)
|
case linkMobileDevice(LinkNewDeviceService.LinkMobileOperation)
|
||||||
case linkDesktopComputer
|
case linkDesktopComputer
|
||||||
case verifyWithAppLockPIN(CheckedContinuation<Bool, Never>)
|
case verifyWithAppLockPIN(CheckedContinuation<Bool, Never>)
|
||||||
case dismiss
|
case dismiss
|
||||||
@@ -44,8 +44,8 @@ final class LinkNewDeviceScreenCoordinator: CoordinatorProtocol {
|
|||||||
|
|
||||||
guard let self else { return }
|
guard let self else { return }
|
||||||
switch action {
|
switch action {
|
||||||
case .linkMobileDevice(let progressPublisher):
|
case .linkMobileDevice(let operation):
|
||||||
actionsSubject.send(.linkMobileDevice(progressPublisher))
|
actionsSubject.send(.linkMobileDevice(operation))
|
||||||
case .linkDesktopComputer:
|
case .linkDesktopComputer:
|
||||||
actionsSubject.send(.linkDesktopComputer)
|
actionsSubject.send(.linkDesktopComputer)
|
||||||
case .verifyWithAppLockPIN(let continuation):
|
case .verifyWithAppLockPIN(let continuation):
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
enum LinkNewDeviceScreenViewModelAction {
|
enum LinkNewDeviceScreenViewModelAction {
|
||||||
case linkMobileDevice(LinkNewDeviceService.LinkMobileProgressPublisher)
|
case linkMobileDevice(LinkNewDeviceService.LinkMobileOperation)
|
||||||
case linkDesktopComputer
|
case linkDesktopComputer
|
||||||
case verifyWithAppLockPIN(CheckedContinuation<Bool, Never>)
|
case verifyWithAppLockPIN(CheckedContinuation<Bool, Never>)
|
||||||
case dismiss
|
case dismiss
|
||||||
|
|||||||
@@ -106,17 +106,17 @@ class LinkNewDeviceScreenViewModel: LinkNewDeviceScreenViewModelType, LinkNewDev
|
|||||||
|
|
||||||
let linkNewDeviceService = clientProxy.linkNewDeviceService()
|
let linkNewDeviceService = clientProxy.linkNewDeviceService()
|
||||||
|
|
||||||
let progressPublisher = linkNewDeviceService.linkMobileDevice()
|
let linkMobileOperation = linkNewDeviceService.linkMobileDevice()
|
||||||
|
|
||||||
do {
|
do {
|
||||||
var iterator = progressPublisher.values.makeAsyncIterator()
|
var iterator = linkMobileOperation.progressPublisher.values.makeAsyncIterator()
|
||||||
while let progress = try await iterator.next(isolation: #isolation) {
|
while let progress = try await iterator.next(isolation: #isolation) {
|
||||||
if case .qrReady = progress {
|
if case .qrReady = progress {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
actionsSubject.send(.linkMobileDevice(progressPublisher))
|
actionsSubject.send(.linkMobileDevice(linkMobileOperation))
|
||||||
state.mode = .readyToLink(.idle)
|
state.mode = .readyToLink(.idle)
|
||||||
} catch {
|
} catch {
|
||||||
// This is hard to share a mapping from the QRCodeLoginError with the
|
// This is hard to share a mapping from the QRCodeLoginError with the
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ enum QRCodeLoginScreenMode {
|
|||||||
/// Configures the screen to link another device by scanning a QR code.
|
/// Configures the screen to link another device by scanning a QR code.
|
||||||
case linkDesktop(LinkNewDeviceServiceProtocol)
|
case linkDesktop(LinkNewDeviceServiceProtocol)
|
||||||
/// Configures the screen to link another device by showing it a QR code.
|
/// Configures the screen to link another device by showing it a QR code.
|
||||||
case linkMobile(LinkNewDeviceService.LinkMobileProgressPublisher)
|
case linkMobile(LinkNewDeviceService.LinkMobileOperation)
|
||||||
}
|
}
|
||||||
|
|
||||||
struct QRCodeLoginScreenViewState: BindableState {
|
struct QRCodeLoginScreenViewState: BindableState {
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ class QRCodeLoginScreenViewModel: QRCodeLoginScreenViewModelType, QRCodeLoginScr
|
|||||||
actionsSubject.eraseToAnyPublisher()
|
actionsSubject.eraseToAnyPublisher()
|
||||||
}
|
}
|
||||||
|
|
||||||
private var currentTask: AnyCancellable?
|
private var currentOperation: CurrentOperation?
|
||||||
private var oAuthResultTask: AnyCancellable?
|
private var oAuthResultTask: AnyCancellable?
|
||||||
private var expirationTask: AnyCancellable?
|
private var expirationTask: AnyCancellable?
|
||||||
|
|
||||||
@@ -38,8 +38,8 @@ class QRCodeLoginScreenViewModel: QRCodeLoginScreenViewModelType, QRCodeLoginScr
|
|||||||
let initialViewState: QRCodeLoginState = switch mode {
|
let initialViewState: QRCodeLoginState = switch mode {
|
||||||
case .login: .loginInstructions
|
case .login: .loginInstructions
|
||||||
case .linkDesktop: .linkDesktopInstructions
|
case .linkDesktop: .linkDesktopInstructions
|
||||||
case .linkMobile(let progressPublisher):
|
case .linkMobile(let operation):
|
||||||
switch progressPublisher.value {
|
switch operation.progressPublisher.value {
|
||||||
case .qrReady(let image): .displayQR(image)
|
case .qrReady(let image): .displayQR(image)
|
||||||
default: .error(.unknown)
|
default: .error(.unknown)
|
||||||
}
|
}
|
||||||
@@ -51,8 +51,8 @@ class QRCodeLoginScreenViewModel: QRCodeLoginScreenViewModelType, QRCodeLoginScr
|
|||||||
switch mode {
|
switch mode {
|
||||||
case .linkDesktop:
|
case .linkDesktop:
|
||||||
scheduleLinkDesktopExpiration()
|
scheduleLinkDesktopExpiration()
|
||||||
case .linkMobile(let progressPublisher):
|
case .linkMobile(let operation):
|
||||||
listenToDisplayQRProgress(progressPublisher: progressPublisher)
|
listenToDisplayQRProgress(operation: operation)
|
||||||
case .login:
|
case .login:
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -62,7 +62,10 @@ class QRCodeLoginScreenViewModel: QRCodeLoginScreenViewModelType, QRCodeLoginScr
|
|||||||
|
|
||||||
override func process(viewAction: QRCodeLoginScreenViewAction) {
|
override func process(viewAction: QRCodeLoginScreenViewAction) {
|
||||||
switch viewAction {
|
switch viewAction {
|
||||||
case .cancel, .errorAction(.cancel):
|
case .cancel:
|
||||||
|
currentOperation?.closeRendezvousChannel()
|
||||||
|
actionsSubject.send(.cancel)
|
||||||
|
case .errorAction(.cancel):
|
||||||
actionsSubject.send(.cancel)
|
actionsSubject.send(.cancel)
|
||||||
case .startScan:
|
case .startScan:
|
||||||
Task { await startScanIfPossible() }
|
Task { await startScanIfPossible() }
|
||||||
@@ -116,19 +119,19 @@ class QRCodeLoginScreenViewModel: QRCodeLoginScreenViewModelType, QRCodeLoginScr
|
|||||||
}
|
}
|
||||||
|
|
||||||
private func handleScan(qrData: Data, loginService: QRCodeLoginServiceProtocol) {
|
private func handleScan(qrData: Data, loginService: QRCodeLoginServiceProtocol) {
|
||||||
guard currentTask == nil else { return }
|
guard currentOperation == nil else { return }
|
||||||
|
|
||||||
state.state = .scan(.connecting)
|
state.state = .scan(.connecting)
|
||||||
|
|
||||||
MXLog.info("Login scanning QR code")
|
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()
|
.removeDuplicates()
|
||||||
.receive(on: DispatchQueue.main)
|
.receive(on: DispatchQueue.main)
|
||||||
.sink { [weak self] completion in
|
.sink { [weak self] completion in
|
||||||
guard let self else { return }
|
guard let self else { return }
|
||||||
currentTask = nil
|
currentOperation = nil
|
||||||
|
|
||||||
switch completion {
|
switch completion {
|
||||||
case .finished: break
|
case .finished: break
|
||||||
@@ -160,22 +163,24 @@ class QRCodeLoginScreenViewModel: QRCodeLoginScreenViewModelType, QRCodeLoginScr
|
|||||||
actionsSubject.send(.signedIn(userSession: session))
|
actionsSubject.send(.signedIn(userSession: session))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
currentOperation = .init(progressCancellable: progressCancellable, closeRendezvousChannelAction: operation.closeRendezvousChannel)
|
||||||
}
|
}
|
||||||
|
|
||||||
private func handleScan(qrData: Data, linkService: LinkNewDeviceServiceProtocol) {
|
private func handleScan(qrData: Data, linkService: LinkNewDeviceServiceProtocol) {
|
||||||
guard currentTask == nil else { return }
|
guard currentOperation == nil else { return }
|
||||||
|
|
||||||
state.state = .scan(.connecting)
|
state.state = .scan(.connecting)
|
||||||
|
|
||||||
MXLog.info("Link scanning QR code")
|
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()
|
.removeDuplicates()
|
||||||
.receive(on: DispatchQueue.main)
|
.receive(on: DispatchQueue.main)
|
||||||
.sink { [weak self] completion in
|
.sink { [weak self] completion in
|
||||||
guard let self else { return }
|
guard let self else { return }
|
||||||
currentTask = nil
|
currentOperation = nil
|
||||||
|
|
||||||
if case .failure(let error) = completion {
|
if case .failure(let error) = completion {
|
||||||
handleError(error)
|
handleError(error)
|
||||||
@@ -204,19 +209,21 @@ class QRCodeLoginScreenViewModel: QRCodeLoginScreenViewModelType, QRCodeLoginScr
|
|||||||
actionsSubject.send(.linkedDevice)
|
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
|
state.bindings.qrResult = nil
|
||||||
|
|
||||||
MXLog.info("Link showing QR code.")
|
MXLog.info("Link showing QR code.")
|
||||||
|
|
||||||
currentTask = progressPublisher
|
let progressCancellable = operation.progressPublisher
|
||||||
.removeDuplicates()
|
.removeDuplicates()
|
||||||
.receive(on: DispatchQueue.main)
|
.receive(on: DispatchQueue.main)
|
||||||
.sink { [weak self] completion in
|
.sink { [weak self] completion in
|
||||||
guard let self else { return }
|
guard let self else { return }
|
||||||
currentTask = nil
|
currentOperation = nil
|
||||||
|
|
||||||
if case .failure(let error) = completion {
|
if case .failure(let error) = completion {
|
||||||
handleError(error)
|
handleError(error)
|
||||||
@@ -244,9 +251,11 @@ class QRCodeLoginScreenViewModel: QRCodeLoginScreenViewModelType, QRCodeLoginScr
|
|||||||
actionsSubject.send(.linkedDevice)
|
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.
|
/// if the secure channel isn't established within the timeout period.
|
||||||
private func scheduleLinkDesktopExpiration() {
|
private func scheduleLinkDesktopExpiration() {
|
||||||
guard case .linkDesktop = state.mode else { fatalError("Expiration requested on an unexpected flow") }
|
guard case .linkDesktop = state.mode else { fatalError("Expiration requested on an unexpected flow") }
|
||||||
@@ -262,12 +271,13 @@ class QRCodeLoginScreenViewModel: QRCodeLoginScreenViewModelType, QRCodeLoginScr
|
|||||||
private func handleExpiration() {
|
private func handleExpiration() {
|
||||||
// Don't override an error that's already being shown.
|
// Don't override an error that's already being shown.
|
||||||
if case .error = state.state {
|
if case .error = state.state {
|
||||||
currentTask = nil // Cancel the scan (just in case).
|
currentOperation = nil // Stop listening for updates (just in case).
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
MXLog.info("Timed out establishing a secure channel, expiring.")
|
MXLog.info("Timed out establishing a secure channel, expiring.")
|
||||||
currentTask = nil // Cancel the scan.
|
currentOperation?.closeRendezvousChannel()
|
||||||
|
currentOperation = nil // Stop listening for updates.
|
||||||
handleError(.expired)
|
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 {
|
extension QRCodeLoginScreenViewModel {
|
||||||
static func mock(state: QRCodeLoginState,
|
static func mock(state: QRCodeLoginState,
|
||||||
mode: QRCodeLoginScreenMode = .login(QRCodeLoginServiceMock()),
|
mode: QRCodeLoginScreenMode = .login(QRCodeLoginServiceMock()),
|
||||||
|
|||||||
@@ -181,7 +181,7 @@ class AuthenticationService: AuthenticationServiceProtocol {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func loginWithQRCode(data: Data) -> QRLoginProgressPublisher {
|
func loginWithQRCode(data: Data) -> QRLoginOperation {
|
||||||
let progressSubject = CurrentValueSubject<QRLoginProgress, AuthenticationServiceError>(.starting)
|
let progressSubject = CurrentValueSubject<QRLoginProgress, AuthenticationServiceError>(.starting)
|
||||||
|
|
||||||
let qrData: QrCodeData
|
let qrData: QrCodeData
|
||||||
@@ -190,7 +190,7 @@ class AuthenticationService: AuthenticationServiceProtocol {
|
|||||||
} catch {
|
} catch {
|
||||||
MXLog.error("QRCode decode error: \(error)")
|
MXLog.error("QRCode decode error: \(error)")
|
||||||
progressSubject.send(completion: .failure(.qrCodeError(.invalidQRCode)))
|
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.
|
// 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.
|
// is not signed in.
|
||||||
MXLog.error("The QR code is from a device that is not yet signed in.")
|
MXLog.error("The QR code is from a device that is not yet signed in.")
|
||||||
progressSubject.send(completion: .failure(.qrCodeError(.deviceNotSignedIn)))
|
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.
|
// 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,
|
let error = QRCodeLoginError.providerNotAllowed(scannedProvider: scannedServerNameOrBaseURL,
|
||||||
allowedProviders: appSettings.accountProviders.map(\.serverNameOrBaseURL))
|
allowedProviders: appSettings.accountProviders.map(\.serverNameOrBaseURL))
|
||||||
progressSubject.send(completion: .failure(.qrCodeError(error)))
|
progressSubject.send(completion: .failure(.qrCodeError(error)))
|
||||||
return progressSubject.asCurrentValuePublisher()
|
return QRLoginOperation(progressPublisher: progressSubject.asCurrentValuePublisher())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -226,11 +226,12 @@ class AuthenticationService: AuthenticationServiceProtocol {
|
|||||||
progressSubject.send(progress)
|
progressSubject.send(progress)
|
||||||
}
|
}
|
||||||
|
|
||||||
Task {
|
let task = Task {
|
||||||
do {
|
do {
|
||||||
let client = try await makeClient(serverNameOrBaseURL: scannedServerNameOrBaseURL)
|
let client = try await makeClient(serverNameOrBaseURL: scannedServerNameOrBaseURL)
|
||||||
let qrCodeHandler = client.newLoginWithQrCodeHandler(oauthConfiguration: appSettings.oAuthConfiguration.rustValue)
|
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) {
|
switch await userSession(for: client) {
|
||||||
case .success(let userSession):
|
case .success(let userSession):
|
||||||
@@ -251,7 +252,7 @@ class AuthenticationService: AuthenticationServiceProtocol {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return progressSubject.asCurrentValuePublisher()
|
return QRLoginOperation(progressPublisher: progressSubject.asCurrentValuePublisher(), task: task)
|
||||||
}
|
}
|
||||||
|
|
||||||
func reset() {
|
func reset() {
|
||||||
|
|||||||
@@ -127,8 +127,25 @@ enum QRCodeLoginError: Error, Equatable {
|
|||||||
|
|
||||||
// sourcery: AutoMockable
|
// sourcery: AutoMockable
|
||||||
protocol QRCodeLoginServiceProtocol {
|
protocol QRCodeLoginServiceProtocol {
|
||||||
typealias QRLoginProgressPublisher = CurrentValuePublisher<QRLoginProgress, AuthenticationServiceError>
|
/// A ``QRCodeOperation`` for logging in by scanning a QR code generated by another device.
|
||||||
func loginWithQRCode(data: Data) -> QRLoginProgressPublisher
|
typealias QRLoginOperation = QRCodeOperation<QRLoginProgress, AuthenticationServiceError>
|
||||||
|
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<Progress, Failure: Error> {
|
||||||
|
let progressPublisher: CurrentValuePublisher<Progress, Failure>
|
||||||
|
private let task: Task<Void, Never>?
|
||||||
|
|
||||||
|
init(progressPublisher: CurrentValuePublisher<Progress, Failure>, task: Task<Void, Never>? = 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 {
|
enum QRLoginProgress {
|
||||||
|
|||||||
@@ -13,16 +13,16 @@ import SwiftUI
|
|||||||
// sourcery: AutoMockable
|
// sourcery: AutoMockable
|
||||||
protocol LinkNewDeviceServiceProtocol {
|
protocol LinkNewDeviceServiceProtocol {
|
||||||
/// Links a new device by showing it a QR code.
|
/// 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.
|
/// 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 {
|
class LinkNewDeviceService: LinkNewDeviceServiceProtocol {
|
||||||
/// Publishes the progress of linking a new device by showing it a QR code.
|
/// A ``QRCodeOperation`` for linking a new device by showing it a QR code.
|
||||||
typealias LinkMobileProgressPublisher = CurrentValuePublisher<LinkMobileProgress, QRCodeLoginError>
|
typealias LinkMobileOperation = QRCodeOperation<LinkMobileProgress, QRCodeLoginError>
|
||||||
/// Publishes the progress of linking a new device by scanning a QR code generated by said device.
|
/// A ``QRCodeOperation`` for linking a new device by scanning a QR code generated by said device.
|
||||||
typealias LinkDesktopProgressPublisher = CurrentValuePublisher<LinkDesktopProgress, QRCodeLoginError>
|
typealias LinkDesktopOperation = QRCodeOperation<LinkDesktopProgress, QRCodeLoginError>
|
||||||
|
|
||||||
/// The progress of linking a new device by showing it a QR code.
|
/// The progress of linking a new device by showing it a QR code.
|
||||||
enum LinkMobileProgress: Equatable {
|
enum LinkMobileProgress: Equatable {
|
||||||
@@ -50,7 +50,7 @@ class LinkNewDeviceService: LinkNewDeviceServiceProtocol {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Links a new device by showing it a QR code.
|
/// Links a new device by showing it a QR code.
|
||||||
func linkMobileDevice() -> LinkMobileProgressPublisher {
|
func linkMobileDevice() -> LinkMobileOperation {
|
||||||
let progressSubject = CurrentValueSubject<LinkMobileProgress, QRCodeLoginError>(.starting)
|
let progressSubject = CurrentValueSubject<LinkMobileProgress, QRCodeLoginError>(.starting)
|
||||||
|
|
||||||
// Bridge from the SDK's synchronous callback into Swift Concurrency. Yielding is safe from
|
// 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() }
|
defer { progressContinuation.finish() }
|
||||||
do {
|
do {
|
||||||
// Note: The SDK doesn't provide us with a way to cancel the grant if the user hit the cancel button 🤷♂️
|
let sdkTask = try grantLoginHandler.generate(progressListener: listener)
|
||||||
try await grantLoginHandler.generate(progressListener: listener).wait() // The success state is handled by the 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
|
// 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)
|
progressSubject.send(LinkMobileProgress.done)
|
||||||
} catch let error as HumanQrGrantLoginError {
|
} 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.
|
/// 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<LinkDesktopProgress, QRCodeLoginError>(.starting)
|
let progressSubject = CurrentValueSubject<LinkDesktopProgress, QRCodeLoginError>(.starting)
|
||||||
|
|
||||||
// Same callback bridging as `linkMobileDevice()` above.
|
// Same callback bridging as `linkMobileDevice()` above.
|
||||||
@@ -121,17 +122,18 @@ class LinkNewDeviceService: LinkNewDeviceServiceProtocol {
|
|||||||
MXLog.error("QR code decode error: \(error)")
|
MXLog.error("QR code decode error: \(error)")
|
||||||
progressSubject.send(completion: .failure(.invalidQRCode))
|
progressSubject.send(completion: .failure(.invalidQRCode))
|
||||||
progressContinuation.finish()
|
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.
|
// 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.
|
// Note the equivalent check will also happen for sign in with QR code in the AuthenticationService.
|
||||||
|
|
||||||
Task {
|
let task = Task {
|
||||||
defer { progressContinuation.finish() }
|
defer { progressContinuation.finish() }
|
||||||
do {
|
do {
|
||||||
// Note: The SDK doesn't provide us with a way to cancel the grant if the user hit the cancel button 🤷♂️
|
let sdkTask = try grantLoginHandler.scan(qrCodeData: qrCodeData, progressListener: listener)
|
||||||
try await grantLoginHandler.scan(qrCodeData: qrCodeData, progressListener: listener).wait() // The success state is handled by the 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
|
// 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)
|
progressSubject.send(LinkDesktopProgress.done)
|
||||||
} catch let error as HumanQrGrantLoginError {
|
} catch let error as HumanQrGrantLoginError {
|
||||||
@@ -143,7 +145,7 @@ class LinkNewDeviceService: LinkNewDeviceServiceProtocol {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return progressSubject.asCurrentValuePublisher()
|
return LinkDesktopOperation(progressPublisher: progressSubject.asCurrentValuePublisher(), task: task)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -751,7 +751,7 @@ class MockScreen: Identifiable {
|
|||||||
return navigationStackCoordinator
|
return navigationStackCoordinator
|
||||||
case .linkNewDevice, .linkNewDeviceWithAppLockPIN:
|
case .linkNewDevice, .linkNewDeviceWithAppLockPIN:
|
||||||
let linkMobileProgressSubject: CurrentValueSubject<LinkNewDeviceService.LinkMobileProgress, QRCodeLoginError> = .init(.qrReady(LinkNewDeviceServiceMock.mockQRCodeImage))
|
let linkMobileProgressSubject: CurrentValueSubject<LinkNewDeviceService.LinkMobileProgress, QRCodeLoginError> = .init(.qrReady(LinkNewDeviceServiceMock.mockQRCodeImage))
|
||||||
let linkNewDeviceService = LinkNewDeviceServiceMock(.init(linkMobileProgressPublisher: linkMobileProgressSubject.asCurrentValuePublisher()))
|
let linkNewDeviceService = LinkNewDeviceServiceMock(.init(linkMobileOperation: .init(progressPublisher: linkMobileProgressSubject.asCurrentValuePublisher())))
|
||||||
|
|
||||||
let clientProxy = ClientProxyMock(.init())
|
let clientProxy = ClientProxyMock(.init())
|
||||||
clientProxy.linkNewDeviceServiceReturnValue = linkNewDeviceService
|
clientProxy.linkNewDeviceServiceReturnValue = linkNewDeviceService
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ class LinkNewDeviceScreenViewModelTests {
|
|||||||
func linkingMobileDeviceVerifiesThenGeneratesQRCode() async throws {
|
func linkingMobileDeviceVerifiesThenGeneratesQRCode() async throws {
|
||||||
// Given a ready screen whose QR code isn't immediately available.
|
// Given a ready screen whose QR code isn't immediately available.
|
||||||
let progressSubject = CurrentValueSubject<LinkNewDeviceService.LinkMobileProgress, QRCodeLoginError>(.starting)
|
let progressSubject = CurrentValueSubject<LinkNewDeviceService.LinkMobileProgress, QRCodeLoginError>(.starting)
|
||||||
setupViewModel(linkMobileProgressPublisher: progressSubject.asCurrentValuePublisher(),
|
setupViewModel(linkMobileOperation: .init(progressPublisher: progressSubject.asCurrentValuePublisher()),
|
||||||
mode: .loading)
|
mode: .loading)
|
||||||
|
|
||||||
// When linking a mobile device.
|
// When linking a mobile device.
|
||||||
@@ -94,7 +94,7 @@ class LinkNewDeviceScreenViewModelTests {
|
|||||||
func linkingWithoutDevicePasscodeOrAppLockPIN() async throws {
|
func linkingWithoutDevicePasscodeOrAppLockPIN() async throws {
|
||||||
// Given a device with neither a passcode nor an App Lock PIN set (device owner verification is unavailable).
|
// Given a device with neither a passcode nor an App Lock PIN set (device owner verification is unavailable).
|
||||||
let progressSubject = CurrentValueSubject<LinkNewDeviceService.LinkMobileProgress, QRCodeLoginError>(.starting)
|
let progressSubject = CurrentValueSubject<LinkNewDeviceService.LinkMobileProgress, QRCodeLoginError>(.starting)
|
||||||
setupViewModel(linkMobileProgressPublisher: progressSubject.asCurrentValuePublisher(),
|
setupViewModel(linkMobileOperation: .init(progressPublisher: progressSubject.asCurrentValuePublisher()),
|
||||||
deviceOwnerResult: .unavailable,
|
deviceOwnerResult: .unavailable,
|
||||||
mode: .loading)
|
mode: .loading)
|
||||||
|
|
||||||
@@ -140,7 +140,7 @@ class LinkNewDeviceScreenViewModelTests {
|
|||||||
func appLockPINVerifiedContinuesLinking() async throws {
|
func appLockPINVerifiedContinuesLinking() async throws {
|
||||||
// Given a device that requires App Lock PIN verification.
|
// Given a device that requires App Lock PIN verification.
|
||||||
let progressSubject = CurrentValueSubject<LinkNewDeviceService.LinkMobileProgress, QRCodeLoginError>(.starting)
|
let progressSubject = CurrentValueSubject<LinkNewDeviceService.LinkMobileProgress, QRCodeLoginError>(.starting)
|
||||||
setupViewModel(linkMobileProgressPublisher: progressSubject.asCurrentValuePublisher(),
|
setupViewModel(linkMobileOperation: .init(progressPublisher: progressSubject.asCurrentValuePublisher()),
|
||||||
deviceOwnerResult: .appLockPINRequired,
|
deviceOwnerResult: .appLockPINRequired,
|
||||||
mode: .loading)
|
mode: .loading)
|
||||||
|
|
||||||
@@ -254,13 +254,13 @@ class LinkNewDeviceScreenViewModelTests {
|
|||||||
// MARK: - Helpers
|
// MARK: - Helpers
|
||||||
|
|
||||||
private func setupViewModel(isLoginWithQRCodeSupported: Bool = true,
|
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,
|
deviceOwnerResult: AppLockDeviceOwnerResult = .verified,
|
||||||
mode: LinkNewDeviceScreenViewState.Mode? = nil) {
|
mode: LinkNewDeviceScreenViewState.Mode? = nil) {
|
||||||
let clientProxy = ClientProxyMock(.init())
|
let clientProxy = ClientProxyMock(.init())
|
||||||
clientProxy.underlyingIsLoginWithQRCodeSupported = isLoginWithQRCodeSupported
|
clientProxy.underlyingIsLoginWithQRCodeSupported = isLoginWithQRCodeSupported
|
||||||
|
|
||||||
linkNewDeviceService = LinkNewDeviceServiceMock(.init(linkMobileProgressPublisher: linkMobileProgressPublisher))
|
linkNewDeviceService = LinkNewDeviceServiceMock(.init(linkMobileOperation: linkMobileOperation))
|
||||||
clientProxy.linkNewDeviceServiceReturnValue = linkNewDeviceService
|
clientProxy.linkNewDeviceServiceReturnValue = linkNewDeviceService
|
||||||
|
|
||||||
appLockService = AppLockServiceMock.mock()
|
appLockService = AppLockServiceMock.mock()
|
||||||
|
|||||||
@@ -223,17 +223,129 @@ struct QRCodeLoginScreenViewModelTests {
|
|||||||
try await deferredAction.fulfill()
|
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
|
// 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<Void, Never>? = nil) {
|
||||||
qrLoginProgressSubject = .init(.starting)
|
qrLoginProgressSubject = .init(.starting)
|
||||||
qrCodeLoginService = QRCodeLoginServiceMock()
|
qrCodeLoginService = QRCodeLoginServiceMock()
|
||||||
qrCodeLoginService.loginWithQRCodeDataReturnValue = qrLoginProgressSubject.asCurrentValuePublisher()
|
qrCodeLoginService.loginWithQRCodeDataReturnValue = .init(progressPublisher: qrLoginProgressSubject.asCurrentValuePublisher(), task: operationTask)
|
||||||
|
|
||||||
linkMobileProgressSubject = .init(.qrReady(LinkNewDeviceServiceMock.mockQRCodeImage))
|
linkMobileProgressSubject = .init(.qrReady(LinkNewDeviceServiceMock.mockQRCodeImage))
|
||||||
linkDesktopProgressSubject = .init(.starting)
|
linkDesktopProgressSubject = .init(.starting)
|
||||||
linkNewDeviceService = LinkNewDeviceServiceMock(.init(linkMobileProgressPublisher: linkMobileProgressSubject.asCurrentValuePublisher(),
|
linkNewDeviceService = LinkNewDeviceServiceMock(.init(linkMobileOperation: .init(progressPublisher: linkMobileProgressSubject.asCurrentValuePublisher(), task: operationTask),
|
||||||
linkDesktopProgressPublisher: linkDesktopProgressSubject.asCurrentValuePublisher()))
|
linkDesktopOperation: .init(progressPublisher: linkDesktopProgressSubject.asCurrentValuePublisher(), task: operationTask)))
|
||||||
|
|
||||||
let screenMode: QRCodeLoginScreenMode
|
let screenMode: QRCodeLoginScreenMode
|
||||||
switch mode {
|
switch mode {
|
||||||
@@ -252,3 +364,12 @@ struct QRCodeLoginScreenViewModelTests {
|
|||||||
linkDesktopTimeout: linkDesktopTimeout)
|
linkDesktopTimeout: linkDesktopTimeout)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private extension QRCodeLoginScreenViewModelAction {
|
||||||
|
var isCancel: Bool {
|
||||||
|
switch self {
|
||||||
|
case .cancel: true
|
||||||
|
default: false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user