Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .github/workflows/unit-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ jobs:
echo "✅ Simulator started at $(date)"

- name: Run unit tests
# Leaves time for the upload below when a slow runner's build ate most of the job's hour
timeout-minutes: 55
run: |
echo "⏱️ Starting unit tests at $(date)"
set -o pipefail && xcodebuild test \
Expand All @@ -56,6 +58,9 @@ jobs:
-skipPackageUpdates \
-enableCodeCoverage NO \
-parallel-testing-enabled NO \
-test-timeouts-enabled YES \
-default-test-execution-time-allowance 300 \
-maximum-test-execution-time-allowance 300 \
-skip-testing:BitkitTests/UtxoSelectionTests \
-skip-testing:BitkitTests/AddressTypeIntegrationTests \
-skip-testing:BitkitTests/RNMigrationCleanupTests \
Expand Down
12 changes: 11 additions & 1 deletion Bitkit/Services/BackupService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1071,8 +1071,18 @@ class BackupService {

private func scheduleBackup(category: BackupCategory, initialOutcome: BackupOutcome = .failed, foregroundGeneration: UInt64? = nil) async {
try? await ServiceQueue.background(.backup) { [self] in
// A request made before a wipe or restore began can arrive after it: drop it, and clear the running flag that
// `markBackupRequired` set for it, which would otherwise keep the category from being scheduled again
guard !shouldSkipBackup(category: category) else {
if backupJobs[category] == nil, runningBackupTasks[category] == nil {
updateBackupStatus(category: category) { status in
BackupItemStatus(synced: status.synced, required: status.required, running: false)
}
}
return
}
if let foregroundGeneration {
guard isObserving, !shouldSkipBackup(category: category),
guard isObserving,
stateQueue.sync(execute: { foregroundObservationGeneration == foregroundGeneration })
else { return }
}
Expand Down
6 changes: 5 additions & 1 deletion Bitkit/Utilities/AppReset.swift
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,11 @@ final class AppReset: WipeStepExecutor {

/// A hung remote cleanup must not hold the wipe; what it leaves behind is recoverable from the seed.
static func runRemoteCleanup(timeout: Duration = .seconds(15), _ cleanup: @escaping () async -> Void) async {
guard await withDeadline(timeout, cleanup) == nil else { return }
await runRemoteCleanup(until: { try await Task.sleep(for: timeout) }, cleanup)
}

static func runRemoteCleanup(until deadline: @escaping () async throws -> Void, _ cleanup: @escaping () async -> Void) async {
guard await withDeadline(until: deadline, cleanup) == nil else { return }
Logger.warn("Remote cleanup timed out, continuing the wipe", context: "AppReset")
}

Expand Down
11 changes: 8 additions & 3 deletions Bitkit/Utilities/Deadline.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,20 @@ import Foundation
/// Returns nil once `timeout` passes, without waiting for an operation that ignores cancellation. The operation is cancelled
/// either way.
func withDeadline<T>(_ timeout: Duration, _ operation: @escaping () async -> T) async -> T? {
await withDeadline(until: { try await Task.sleep(for: timeout) }, operation)
}

/// Returns nil once `deadline` returns, like `withDeadline(_:_:)` with a deadline other than a clock's.
func withDeadline<T>(until deadline: @escaping () async throws -> Void, _ operation: @escaping () async -> T) async -> T? {
let (results, continuation) = AsyncStream<T?>.makeStream(bufferingPolicy: .bufferingOldest(1))
let work = Task { await continuation.yield(operation()) }
let deadline = Task {
try await Task.sleep(for: timeout)
let deadlineTask = Task {
try await deadline()
continuation.yield(nil)
}
defer {
work.cancel()
deadline.cancel()
deadlineTask.cancel()
continuation.finish()
}

Expand Down
5 changes: 2 additions & 3 deletions BitkitTests/BackupServiceTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -222,10 +222,9 @@ final class BackupServiceTests: XCTestCase {
}

func testTemporaryFailureRemainsPendingAcrossServiceRestart() async throws {
let suite = "BackupServiceTests.\(UUID().uuidString)"
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite) }
for category in [BackupCategory.wallet, .usdt] {
// Its own suite per category: a stopped service's jobs can still rewrite the statuses of the suite it used
let defaults = try makeIsolatedDefaults("\(#function).\(category)")
let unavailable = BackupService(defaults: defaults, backupData: { _ in
throw PaykitError.SharedStateBusy(code: "shared_state_busy", context: "pending reconciliation")
}, waitForBackupDelay: { try await Task.sleep(nanoseconds: 60_000_000_000) })
Expand Down
26 changes: 25 additions & 1 deletion BitkitTests/PaykitPaymentRequestServiceTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3108,7 +3108,7 @@ final class PaykitPaymentRequestServiceTests: XCTestCase {
to: target
)
}
try await waitUntil { await sdk.uploadIsPaused() }
try await waitUntil(before: proposal) { await sdk.uploadIsPaused() }
switch change {
case "expired": clock.advance(by: 60)
case "removed": await manager.refreshEligibleTargets(savedPublicKeys: [])
Expand Down Expand Up @@ -11540,6 +11540,7 @@ private final class PaymentRequestTestClock: @unchecked Sendable {

private enum PaymentRequestTestError: Error {
case timedOut
case endedFirst
}

private actor PaymentProofProtectionGate {
Expand Down Expand Up @@ -11630,6 +11631,29 @@ private final class PaymentRequestIntakeError: PrivateOperationError, @unchecked
}
}

/// Polls with no time limit, as on a slow runner `condition` can take seconds to hold, and fails at once when `operation`
/// ends without it holding.
@MainActor
private func waitUntil(before operation: Task<some Sendable, Error>, condition: @MainActor () async -> Bool) async throws {
let ended = OperationEndFlag()
Task { @MainActor in
_ = await operation.result
ended.isSet = true
}
while await !condition() {
guard !ended.isSet else {
guard await condition() else { throw PaymentRequestTestError.endedFirst }
return
}
try await Task.sleep(for: .milliseconds(10))
}
}

@MainActor
private final class OperationEndFlag {
var isSet = false
}

@MainActor
private func waitUntil(
timeout: Duration = .seconds(2),
Expand Down
13 changes: 8 additions & 5 deletions BitkitTests/PaykitSdkIdentityCheckTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -975,12 +975,15 @@ final class PaykitSdkIdentityCheckTests: XCTestCase {
try Keychain.upsert(key: .pubkySecretKey, data: Data(oldSecret.utf8))

let readEntered = expectation(description: "the old cleanup is reading SDK state")
let cleanupEnded = expectation(description: "the abandoned cleanup returns")
// The wipe stops waiting once the cleanup is held in its read, however long the cleanup takes to get there
let readEnteredGate = AsyncGate()
let cleanupEnded = AsyncGate()
let readGate = AsyncGate()
defer { readGate.open() }
let oldSdk = AbandonedCleanupSdk(noPointer: .init())
let suspendRead = {
readEntered.fulfill()
readEnteredGate.open()
// Like the UniFFI call, it ignores Swift cancellation
await readGate.wait()
}
Expand All @@ -1002,7 +1005,7 @@ final class PaykitSdkIdentityCheckTests: XCTestCase {

let wipe = Task {
try await service.withWalletWipe {
await AppReset.runRemoteCleanup(timeout: .milliseconds(100)) {
await AppReset.runRemoteCleanup(until: { await readEnteredGate.wait() }) {
switch heldRead {
case .registry, .revision:
_ = try? await service.syncPublicEndpoints([])
Expand All @@ -1011,15 +1014,15 @@ final class PaykitSdkIdentityCheckTests: XCTestCase {
case .peers, .linkRecovery:
_ = try? await service.clearPrivatePaymentLists(to: oldSdk.recoveringPeers, isSessionCurrent: { !Task.isCancelled })
}
cleanupEnded.fulfill()
cleanupEnded.open()
}
// The wipe clears these once it has stopped waiting for the cleanup
try Keychain.delete(key: .pubkySecretKey)
try Keychain.delete(key: oldGenerationKey)
}
}
await fulfillment(of: [readEntered], timeout: 2)
try await wipe.value
await fulfillment(of: [readEntered], timeout: 0)
XCTAssertNil(try Keychain.load(key: oldGenerationKey))

// The next wallet's first operation creates its own SDK and identity before the old response arrives
Expand All @@ -1029,7 +1032,7 @@ final class PaykitSdkIdentityCheckTests: XCTestCase {
XCTAssertTrue(replacementSdk.mutations.isEmpty)

readGate.open()
await fulfillment(of: [cleanupEnded], timeout: 2)
await cleanupEnded.wait()

XCTAssertNil(try Keychain.load(key: oldGenerationKey), "Completed wipe must not recreate the old identity's keychain state")
let alreadyStartedMutations = heldRead == .linkRecovery ? ["recoverLink"] : []
Expand Down
40 changes: 32 additions & 8 deletions BitkitTests/ProfileDestinationViewTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -282,12 +282,12 @@ final class ProfileDestinationViewTests: XCTestCase {
defer { disconnectGate.finish() }
let disconnect = Task {
try await manager.signOut {
disconnectGate.started.fulfill()
disconnectGate.markStarted()
for await _ in disconnectGate.stream {}
throw PubkyServiceError.sessionNotActive
}
}
await fulfillment(of: [disconnectGate.started], timeout: 3)
await disconnectGate.assertReached(by: disconnect)
try await Task.sleep(for: .milliseconds(100))
XCTAssertEqual(manager.profileForDisplay?.name, profile.name)
disconnectGate.finish()
Expand All @@ -311,7 +311,7 @@ final class ProfileDestinationViewTests: XCTestCase {
let retryGate = await response.holdNextRequest()
defer { retryGate.finish() }
let retry = Task { await manager.loadProfile() }
await fulfillment(of: [retryGate.started], timeout: 3)
await retryGate.assertReached(by: retry)
XCTAssertTrue(manager.isLoadingProfile)
XCTAssertEqual(manager.profileForDisplay?.name, profile.name)
retryGate.finish()
Expand Down Expand Up @@ -437,7 +437,7 @@ private final class ContactsRecoveryProfileManager: PubkyProfileManager {
}

override func hasExistingIdentityForNavigation(hasStoredIdentity: @escaping @Sendable () throws -> Bool) async -> Bool {
lookup.started.fulfill()
lookup.markStarted()
for await _ in lookup.stream {}
return identityExists
}
Expand All @@ -449,7 +449,7 @@ private final class ContactsRecoveryProfileManager: PubkyProfileManager {
didAttemptRecovery = true
let gate = restoration
await super.restoreSessionIfNeeded(hasStoredIdentity: { true }) {
gate.started.fulfill()
gate.markStarted()
for await _ in gate.stream {}
return .restorationFailed
}
Expand Down Expand Up @@ -486,10 +486,34 @@ private struct ProfileOperationGate {
let started: XCTestExpectation
let stream: AsyncStream<Void>
private let continuation: AsyncStream<Void>.Continuation
private let reachedEvents: AsyncStream<Bool>
private let reachedContinuation: AsyncStream<Bool>.Continuation

init(name: String) {
started = XCTestExpectation(description: name)
(stream, continuation) = AsyncStream<Void>.makeStream()
(reachedEvents, reachedContinuation) = AsyncStream<Bool>.makeStream()
}

func markStarted() {
started.fulfill()
reachedContinuation.yield(true)
}

/// Waits with no time limit, as on a slow runner the operation can take seconds to reach the gate, and fails at once when
/// `operation` ends without reaching it.
func assertReached(by operation: Task<some Sendable, some Error>, file: StaticString = #filePath, line: UInt = #line) async {
let events = reachedContinuation
Task {
_ = await operation.result
events.yield(false)
}
var reached = false
for await event in reachedEvents {
reached = event
break
}
XCTAssertTrue(reached, "\(started.expectationDescription) ended before reaching its gate", file: file, line: line)
}

func finish() {
Expand Down Expand Up @@ -518,7 +542,7 @@ private actor ProfileResponse {
func resolve() async throws -> PubkyProfile {
if let gate {
self.gate = nil
gate.started.fulfill()
gate.markStarted()
for await _ in gate.stream {}
}
guard let profile else { throw URLError(.notConnectedToInternet) }
Expand All @@ -537,7 +561,7 @@ private final class SuspendedProfileManager: PubkyProfileManager {
) async {
let gate = restoration
await super.restoreSessionIfNeeded(hasStoredIdentity: { true }) {
gate.started.fulfill()
gate.markStarted()
for await _ in gate.stream {}
throw PubkyServiceError.authFailed("offline")
}
Expand All @@ -547,7 +571,7 @@ private final class SuspendedProfileManager: PubkyProfileManager {
isLoadingProfile = true
defer { isLoadingProfile = false }
let gate = profileFetch
gate.started.fulfill()
gate.markStarted()
for await _ in gate.stream {}
}
}
37 changes: 29 additions & 8 deletions BitkitTests/ServerConnectionResetTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ final class ServerConnectionResetTests: XCTestCase {
restartCount += 1
}
}
await fulfillment(of: [endpoint.started], timeout: 3)
await endpoint.assertReached(by: connection)

clearServerPreferencesAndReset()
settings.rgsIsLoading = true
Expand All @@ -56,7 +56,7 @@ final class ServerConnectionResetTests: XCTestCase {
throw TestError.restartFailed
}
}
await fulfillment(of: [restart.started], timeout: 3)
await restart.assertReached(by: connection)
clearServerPreferencesAndReset()
settings.rgsIsLoading = true
restart.resume(())
Expand Down Expand Up @@ -89,7 +89,7 @@ final class ServerConnectionResetTests: XCTestCase {
waitCount += 1
}, isNodeRunning: { true })
}
await fulfillment(of: [restart.started], timeout: 3)
await restart.assertReached(by: connection)
clearServerPreferencesAndReset()
settings.electrumHost = "new.example.com"
settings.electrumIsLoading = true
Expand All @@ -112,7 +112,7 @@ final class ServerConnectionResetTests: XCTestCase {
await wait.wait()
}, isNodeRunning: { true })
}
await fulfillment(of: [wait.started], timeout: 3)
await wait.assertReached(by: connection)
clearServerPreferencesAndReset()
wait.resume(())

Expand Down Expand Up @@ -140,7 +140,8 @@ final class ServerConnectionResetTests: XCTestCase {
await electrumRestart.wait()
}, waitForConnection: {}, isNodeRunning: { true })
}
await fulfillment(of: [restart.started, electrumRestart.started], timeout: 3)
await restart.assertReached(by: connection)
await electrumRestart.assertReached(by: electrumConnection)

let invalidated = expectation(description: "Wipe invalidates the pending connection")
let observation = settings.$rgsIsLoading.dropFirst().filter { !$0 }.first().sink { _ in invalidated.fulfill() }
Expand Down Expand Up @@ -247,7 +248,7 @@ final class ServerConnectionResetTests: XCTestCase {
XCTFail("Cancelled request must not restart the node")
})
}
await fulfillment(of: [endpoint.started], timeout: 3)
await endpoint.assertReached(by: connection)
connection.cancel()
endpoint.resume(true)

Expand All @@ -273,20 +274,40 @@ final class ServerConnectionResetTests: XCTestCase {
}
}

/// Holds a connection at one of its suspension points. Waiting for it to get there has no time limit: on a slow runner it
/// can take seconds, and a connection that returns without getting there fails the test at once.
@MainActor
private final class ConnectionGate<Value> {
let started = XCTestExpectation(description: "Connection reached suspended operation")
private var continuation: CheckedContinuation<Value, Never>?
private var hasStarted = false
private var reachedWaiter: CheckedContinuation<Bool, Never>?

func wait() async -> Value {
await withCheckedContinuation {
continuation = $0
started.fulfill()
hasStarted = true
reachedWaiter?.resume(returning: true)
reachedWaiter = nil
}
}

func resume(_ value: Value) {
continuation?.resume(returning: value)
continuation = nil
}

func assertReached(by connection: Task<some Sendable, Never>, file: StaticString = #filePath, line: UInt = #line) async {
let reached = await reached(by: connection)
XCTAssertTrue(reached, "The connection returned before reaching the gate", file: file, line: line)
}

private func reached(by connection: Task<some Sendable, Never>) async -> Bool {
guard !hasStarted else { return true }
Task {
_ = await connection.value
reachedWaiter?.resume(returning: hasStarted)
reachedWaiter = nil
}
return await withCheckedContinuation { reachedWaiter = $0 }
}
}
Loading
Loading