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
4 changes: 4 additions & 0 deletions Bitkit/BitkitApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
30 changes: 19 additions & 11 deletions Bitkit/Managers/UsdtWalletManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand All @@ -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(
Expand Down Expand Up @@ -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)
}
}
}

Expand All @@ -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)
}
}
}

Expand All @@ -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())
Expand Down Expand Up @@ -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? {
Expand All @@ -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() }
}
}

Expand All @@ -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 }
Expand Down
8 changes: 5 additions & 3 deletions Bitkit/Services/CoreService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down
84 changes: 84 additions & 0 deletions Bitkit/Services/ServiceQueue.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Foundation
import UIKit

/// Handles app services each on it's own dedicated queue
class ServiceQueue {
Expand Down Expand Up @@ -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
Expand All @@ -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))
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand All @@ -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<T>(_ 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<T>(_ 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 }
}
2 changes: 1 addition & 1 deletion Bitkit/Utilities/AppReset.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 3 additions & 2 deletions Bitkit/ViewModels/BlocktankViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}

Expand Down
Loading
Loading