diff --git a/Bitkit/BitkitApp.swift b/Bitkit/BitkitApp.swift index 5b7c7e975..f13695939 100644 --- a/Bitkit/BitkitApp.swift +++ b/Bitkit/BitkitApp.swift @@ -72,6 +72,10 @@ class AppDelegate: NSObject, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { + BackgroundTime.beginTask = { name, expiration in + UIApplication.shared.beginBackgroundTask(withName: name, expirationHandler: expiration) + } + BackgroundTime.endTask = { UIApplication.shared.endBackgroundTask($0) } UNUserNotificationCenter.current().delegate = self SparkExitManager.registerBackgroundTask() diff --git a/Bitkit/Managers/UsdtWalletManager.swift b/Bitkit/Managers/UsdtWalletManager.swift index 84dccd744..ec4d24596 100644 --- a/Bitkit/Managers/UsdtWalletManager.swift +++ b/Bitkit/Managers/UsdtWalletManager.swift @@ -102,7 +102,7 @@ final class UsdtWalletManager { guard !isSendPresented else { throw UsdtWalletError.cannotDisable } let wallet = try await wallet() balance = try await wallet.balance() - transfers = try await wallet.refreshTransfers() + transfers = try await BackgroundTime.during("usdt refreshTransfers") { try await wallet.refreshTransfers() } guard !UsdtPreference.protectsFunds(balance: balance, transfers: transfers) else { throw UsdtWalletError.cannotDisable } if depositsConfigured { var offset: UInt32 = 0 @@ -194,7 +194,7 @@ final class UsdtWalletManager { var settlementError: Error? do { balance = try await wallet.balance() - transfers = try await wallet.refreshTransfers() + transfers = try await BackgroundTime.during("usdt refreshTransfers") { try await wallet.refreshTransfers() } } catch is CancellationError { throw CancellationError() } catch { @@ -207,7 +207,7 @@ final class UsdtWalletManager { if historyRefreshRequested, !isSendPresented, now() >= nextHistoryRefresh { historyRefreshRequested = false nextHistoryRefresh = now().addingTimeInterval(10) - let complete = try await wallet.syncHistory() + let complete = try await BackgroundTime.during("usdt syncHistory") { try await wallet.syncHistory() } historyComplete = historyComplete || complete transfers = try await ServiceQueue.background(.core, wrapErrors: false) { try wallet.history() } let received = Self.newIncomingTransfers( @@ -281,7 +281,9 @@ final class UsdtWalletManager { if recipient.trimmingCharacters(in: .whitespacesAndNewlines).caseInsensitiveCompare(wallet.receiveAddress()) == .orderedSame { throw UsdtWalletError.selfSend } - return try await wallet.quoteTransfer(recipient: recipient, amount: value, destination: destination) + return try await BackgroundTime.during("usdt quoteTransfer") { + try await wallet.quoteTransfer(recipient: recipient, amount: value, destination: destination) + } } } @@ -293,7 +295,9 @@ final class UsdtWalletManager { if recipient.trimmingCharacters(in: .whitespacesAndNewlines).caseInsensitiveCompare(wallet.receiveAddress()) == .orderedSame { throw UsdtWalletError.selfSend } - return try await wallet.quoteMaxTransfer(recipient: recipient, destination: destination) + return try await BackgroundTime.during("usdt quoteMaxTransfer") { + try await wallet.quoteMaxTransfer(recipient: recipient, destination: destination) + } } } @@ -309,12 +313,12 @@ final class UsdtWalletManager { try beginOperation(requiresNetwork: false) defer { finishOperation() } let wallet = try await wallet(requiresNetwork: false) - try await wallet.restoreBackup(snapshot: snapshot) + try await BackgroundTime.during("usdt restoreBackup") { try await wallet.restoreBackup(snapshot: snapshot) } displayBalanceCache.clear() cachedBalance = nil balance = nil pendingDepositIds.removeAll() - transfers = try wallet.history() + transfers = try BackgroundTime.during("usdt history") { try wallet.history() } historyComplete = false if receiptsSince == nil { receiptsSince = Self.receiptBaseline(now()) @@ -373,7 +377,9 @@ final class UsdtWalletManager { defer { finishOperation() } let core = try await wallet() let credentials = try await loadCredentials() - return try await core.createPaymentProof(transferId: quoteId, binding: binding, mnemonic: credentials.0, passphrase: credentials.1) + return try await BackgroundTime.during("usdt createPaymentProof") { + try await core.createPaymentProof(transferId: quoteId, binding: binding, mnemonic: credentials.0, passphrase: credentials.1) + } } func storedTransfer(_ id: String) async throws -> UsdtTransfer? { @@ -391,9 +397,10 @@ final class UsdtWalletManager { defer { refreshing = false } try await withRateLimit { let wallet = try await wallet() - guard let transfer = try wallet.history().first(where: { $0.id == id }) else { throw UsdtError.InvalidBackup } + let history = try BackgroundTime.during("usdt history") { try wallet.history() } + guard let transfer = history.first(where: { $0.id == id }) else { throw UsdtError.InvalidBackup } guard transfer.status == .pending else { return } - transfers = try await wallet.refreshTransfers() + transfers = try await BackgroundTime.during("usdt refreshTransfers") { try await wallet.refreshTransfers() } } } @@ -415,7 +422,8 @@ final class UsdtWalletManager { let deadline = clock.now.advanced(by: .seconds(5)) while clock.now < deadline { try Task.checkCancellation() - let transfer = try await Task.detached { try await wallet.checkRecentExecution(id: id) }.value + let transfer = try await Task + .detached { try await BackgroundTime.during("usdt checkRecentExecution") { try await wallet.checkRecentExecution(id: id) } }.value try Task.checkCancellation() guard let transfer else { return } transfers.removeAll { $0.id == transfer.id } diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index da9d481ce..595383b89 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -223,7 +223,7 @@ class ActivityService { func isActivitySeen(id: String, walletId: String = WalletScope.default) async -> Bool { do { - if let activity = try getActivityById(walletId: walletId, activityId: id) { + if let activity = try BackgroundTime.during("isActivitySeen", { try getActivityById(walletId: walletId, activityId: id) }) { switch activity { case let .onchain(onchain): return onchain.seenAt != nil @@ -1184,7 +1184,9 @@ class ActivityService { } } - let closedChannels = try getAllClosedChannels(sortDirection: .desc) + let closedChannels = try BackgroundTime.during("findClosedChannelForTransaction") { + try getAllClosedChannels(sortDirection: .desc) + } guard !closedChannels.isEmpty else { return nil } let details = if let provided = transactionDetails { @@ -2765,7 +2767,7 @@ class CoreService { private init(walletIndex: Int = 0) { self.walletIndex = walletIndex - _ = try! initDb(basePath: Env.bitkitCoreStorage(walletIndex: walletIndex).path) + _ = try! BackgroundTime.during("initDb") { try initDb(basePath: Env.bitkitCoreStorage(walletIndex: walletIndex).path) } // First thing ever added to the core queue so guarenteed to run first before any of above functions on the same queue ServiceQueue.background(.core) { diff --git a/Bitkit/Services/ServiceQueue.swift b/Bitkit/Services/ServiceQueue.swift index ffd6ceebb..a607f8a1f 100644 --- a/Bitkit/Services/ServiceQueue.swift +++ b/Bitkit/Services/ServiceQueue.swift @@ -1,4 +1,5 @@ import Foundation +import UIKit /// Handles app services each on it's own dedicated queue class ServiceQueue { @@ -31,6 +32,16 @@ class ServiceQueue { return ServiceQueue.backupQueue } } + + /// bitkit-core's SQLite databases live in the app group container, and iOS kills an app suspended while it holds a lock on + /// such a file (0xdead10cc). Work on these queues therefore keeps the app running in the background until it ends. + var usesDatabases: Bool { + self == .core || self == .migration + } + } + + private static func requestBackgroundTime(for service: ServiceTypes, functionName: String) -> BackgroundTime? { + service.usesDatabases ? BackgroundTime(name: "\(service) \(functionName)") : nil } /// Executes a thread blocking function on chosen service queue @@ -43,8 +54,10 @@ class ServiceQueue { functionName: String = #function) async throws -> T { let startTime = CFAbsoluteTimeGetCurrent() + let backgroundTime = requestBackgroundTime(for: service, functionName: functionName) let result = try await withCheckedThrowingContinuation { continuation in service.queue.async { + defer { backgroundTime?.end() } do { let res = try blocking() continuation.resume(with: .success(res)) @@ -71,9 +84,11 @@ class ServiceQueue { { let startTime = CFAbsoluteTimeGetCurrent() + let backgroundTime = requestBackgroundTime(for: service, functionName: functionName) return try await withCheckedThrowingContinuation { continuation in service.queue.async { Task { + defer { backgroundTime?.end() } do { let result = try await execute() continuation.resume(returning: result) @@ -111,7 +126,9 @@ class ServiceQueue { ) { let startTime = CFAbsoluteTimeGetCurrent() + let backgroundTime = requestBackgroundTime(for: service, functionName: functionName) service.queue.async { + defer { backgroundTime?.end() } do { let result = try execute() let timeElapsed = Double(round(100 * (CFAbsoluteTimeGetCurrent() - startTime)) / 100) @@ -137,8 +154,10 @@ class ServiceQueue { ) { let startTime = CFAbsoluteTimeGetCurrent() + let backgroundTime = requestBackgroundTime(for: service, functionName: functionName) service.queue.async { Task { + defer { backgroundTime?.end() } do { let result = try await execute() let timeElapsed = Double(round(100 * (CFAbsoluteTimeGetCurrent() - startTime)) / 100) @@ -153,3 +172,68 @@ class ServiceQueue { } } } + +/// Asks iOS for background running time until `end()` is called, the instance is released or the time expires. +/// Its state is guarded by `lock`. +final class BackgroundTime: @unchecked Sendable { + typealias Begin = (_ name: String, _ expiration: @escaping () -> Void) -> UIBackgroundTaskIdentifier + typealias End = (UIBackgroundTaskIdentifier) -> Void + + private let lock = NSLock() + private let endTask: End + private var identifier: UIBackgroundTaskIdentifier = .invalid + private var ended = false + + init(name: String, begin: Begin? = nil, end: End? = nil) { + let begin = begin ?? BackgroundTime.beginTask + let end = end ?? BackgroundTime.endTask + endTask = end + let identifier = begin(name) { [weak self] in + self?.end() + } + // The expiration handler can run before the identifier is stored. + let endedAlready = lock.withLock { + if !ended { + self.identifier = identifier + } + return ended + } + if endedAlready, identifier != .invalid { + end(identifier) + } + } + + deinit { + end() + } + + func end() { + let identifier = lock.withLock { + ended = true + defer { self.identifier = .invalid } + return self.identifier + } + if identifier != .invalid { + endTask(identifier) + } + } + + /// Runs `body` with background running time, for database work outside `ServiceQueue`'s database queues. + static func during(_ name: String, _ body: () async throws -> T) async rethrows -> T { + let backgroundTime = BackgroundTime(name: name) + defer { backgroundTime.end() } + return try await body() + } + + /// Runs `body` with background running time, for database work outside `ServiceQueue`'s database queues. + static func during(_ name: String, _ body: () throws -> T) rethrows -> T { + let backgroundTime = BackgroundTime(name: name) + defer { backgroundTime.end() } + return try body() + } + + /// The app sets these at launch. The notification extension, which compiles this file too, has no `UIApplication`, so its + /// work runs without background time. + nonisolated(unsafe) static var beginTask: Begin = { _, _ in .invalid } + nonisolated(unsafe) static var endTask: End = { _ in } +} diff --git a/Bitkit/Utilities/AppReset.swift b/Bitkit/Utilities/AppReset.swift index de1529e88..9d97fea2f 100644 --- a/Bitkit/Utilities/AppReset.swift +++ b/Bitkit/Utilities/AppReset.swift @@ -98,7 +98,7 @@ final class AppReset: WipeStepExecutor { case .wipeDatabases: // bitkit-core wipes only databases it has opened, which `CoreService` does when it is created. _ = CoreService.shared - let coreWipeResult = try await wipeAllDatabases() + let coreWipeResult = try await BackgroundTime.during("wipeAllDatabases") { try await wipeAllDatabases() } Logger.info("Core DB wipe: \(coreWipeResult)") case .clearPubkyState: // Clear any live Pubky runtime state and cached profile images. diff --git a/Bitkit/ViewModels/BlocktankViewModel.swift b/Bitkit/ViewModels/BlocktankViewModel.swift index 3dc238235..096dc9818 100644 --- a/Bitkit/ViewModels/BlocktankViewModel.swift +++ b/Bitkit/ViewModels/BlocktankViewModel.swift @@ -65,8 +65,9 @@ class BlocktankViewModel: ObservableObject { } func refreshInfo() async throws { - info = try await getInfo(refresh: false) // Instant set cached info to state before refreshing - info = try await getInfo(refresh: true) + info = try await BackgroundTime + .during("blocktank getInfo") { try await getInfo(refresh: false) } // Instant set cached info to state before refreshing + info = try await BackgroundTime.during("blocktank getInfo") { try await getInfo(refresh: true) } coreService.blocktank.notifyStateChanged() } diff --git a/BitkitTests/BackgroundTimeTests.swift b/BitkitTests/BackgroundTimeTests.swift new file mode 100644 index 000000000..5ba751ee9 --- /dev/null +++ b/BitkitTests/BackgroundTimeTests.swift @@ -0,0 +1,120 @@ +@testable import Bitkit +import UIKit +import XCTest + +final class BackgroundTimeTests: XCTestCase { + private final class FakeTasks: @unchecked Sendable { + let lock = NSLock() + var began: [String] = [] + var ended: [UIBackgroundTaskIdentifier] = [] + var expiration: (() -> Void)? + var expireOnBegin = false + + func begin(name: String, expiration: @escaping () -> Void) -> UIBackgroundTaskIdentifier { + lock.withLock { + began.append(name) + self.expiration = expiration + } + if expireOnBegin { + expiration() + } + return UIBackgroundTaskIdentifier(rawValue: 7) + } + + func end(_ identifier: UIBackgroundTaskIdentifier) { + lock.withLock { ended.append(identifier) } + } + + func make(_ name: String = "work") -> BackgroundTime { + BackgroundTime(name: name, begin: begin, end: end) + } + } + + func testEndEndsTheTaskOnce() { + let tasks = FakeTasks() + let backgroundTime = tasks.make() + + backgroundTime.end() + backgroundTime.end() + + XCTAssertEqual(tasks.began, ["work"]) + XCTAssertEqual(tasks.ended, [UIBackgroundTaskIdentifier(rawValue: 7)]) + } + + func testExpirationEndsTheTask() { + let tasks = FakeTasks() + let backgroundTime = tasks.make() + + tasks.expiration?() + backgroundTime.end() + + XCTAssertEqual(tasks.ended, [UIBackgroundTaskIdentifier(rawValue: 7)]) + } + + func testExpirationBeforeTheIdentifierIsStoredStillEndsTheTask() { + let tasks = FakeTasks() + tasks.expireOnBegin = true + + let backgroundTime = tasks.make() + backgroundTime.end() + + XCTAssertEqual(tasks.ended, [UIBackgroundTaskIdentifier(rawValue: 7)]) + } + + func testReleasingEndsTheTask() { + let tasks = FakeTasks() + _ = tasks.make() + + XCTAssertEqual(tasks.ended, [UIBackgroundTaskIdentifier(rawValue: 7)]) + } + + func testWithoutTheAppsHooksNoTaskIsEnded() { + let tasks = FakeTasks() + let backgroundTime = BackgroundTime(name: "work", begin: { _, _ in .invalid }, end: tasks.end) + + backgroundTime.end() + + XCTAssertEqual(tasks.ended, []) + } + + /// Runs `body` with `tasks` installed as the app's hooks. + private func withHooks(_ tasks: FakeTasks, _ body: () async throws -> Void) async rethrows { + let (begin, end) = (BackgroundTime.beginTask, BackgroundTime.endTask) + BackgroundTime.beginTask = tasks.begin + BackgroundTime.endTask = tasks.end + defer { (BackgroundTime.beginTask, BackgroundTime.endTask) = (begin, end) } + try await body() + } + + func testDuringEndsTheTaskAlsoWhenTheBodyThrows() async { + struct Failure: Error {} + let tasks = FakeTasks() + + await withHooks(tasks) { + _ = try? await BackgroundTime.during("quote") { () async throws -> Int in throw Failure() } + } + + XCTAssertEqual(tasks.began, ["quote"]) + XCTAssertEqual(tasks.ended, [UIBackgroundTaskIdentifier(rawValue: 7)]) + } + + func testDatabaseQueueWorkHoldsBackgroundTimeUntilItEnds() async throws { + let tasks = FakeTasks() + + try await withHooks(tasks) { + _ = try await ServiceQueue.background(.core) { 1 } + _ = try await ServiceQueue.background(.ldk) { 1 } + } + + XCTAssertEqual(tasks.began.count, 1) + XCTAssertEqual(tasks.ended, [UIBackgroundTaskIdentifier(rawValue: 7)]) + } + + func testOnlyDatabaseQueuesAskForBackgroundTime() { + XCTAssertTrue(ServiceQueue.ServiceTypes.core.usesDatabases) + XCTAssertTrue(ServiceQueue.ServiceTypes.migration.usesDatabases) + XCTAssertFalse(ServiceQueue.ServiceTypes.ldk.usesDatabases) + XCTAssertFalse(ServiceQueue.ServiceTypes.forex.usesDatabases) + XCTAssertFalse(ServiceQueue.ServiceTypes.backup.usesDatabases) + } +} diff --git a/changelog.d/next/1126.fixed.md b/changelog.d/next/1126.fixed.md new file mode 100644 index 000000000..9ed310f40 --- /dev/null +++ b/changelog.d/next/1126.fixed.md @@ -0,0 +1 @@ +Fixed iOS closing the app when it goes to the background during wallet database work.