diff --git a/DashWallet/Sources/Models/CrowdNode/CrowdNode.swift b/DashWallet/Sources/Models/CrowdNode/CrowdNode.swift index b340720e22..efe02bb8dc 100644 --- a/DashWallet/Sources/Models/CrowdNode/CrowdNode.swift +++ b/DashWallet/Sources/Models/CrowdNode/CrowdNode.swift @@ -200,8 +200,16 @@ public final class CrowdNode { // MARK: Restoring state extension CrowdNode { func restoreState() { + // The pass scans the persisted history twice with identical arguments + // (`tryRestoreSignUp`, then `getApiAddressConfirmationTx`). On a wallet + // with thousands of transactions that is two full fetch+decode walks + // of the same rows, ~12s each on the calling thread — share one. + TransactionObserver.withSharedScan { performRestoreState() } + } + + private func performRestoreState() { checkAPY() - + if signUpState > SignUpState.notStarted { // Already started/restored return @@ -1049,10 +1057,15 @@ extension CrowdNode { let filter = CoinsToAddressTxFilter(coins: CrowdNode.apiConfirmationDashAmount, address: nil) // account address is unknown at this point let forwardedConfirmationFilter = CrowdNodeAPIConfirmationTxForwarded() // Same floor the signup scan uses: an API-address confirmation is - // CrowdNode protocol traffic, so it cannot predate CrowdNode. Without - // it this walked and decoded the wallet's entire history on the main - // thread during restore — the more expensive of the restore's two - // scans, on a wallet that has no CrowdNode account at all. + // CrowdNode protocol traffic, so it cannot predate CrowdNode. + // + // TODO(crowdnode-restore-floor): the floor bounds `firstSeen`, which + // the SDK stamps from the device clock when it first observes a row — + // so on a restored wallet every row is "first seen" now and the floor + // admits the entire history regardless of its chain date. Bounding on + // `blockTimestamp` (falling back to `firstSeen` while unconfirmed) + // would restore the intent; it needs a SwiftData predicate change that + // has to be verified against the store rather than reasoned about. let observed = TransactionObserver.fetchObserved( firstSeenAtOrAfter: FullCrowdNodeSignUpTxSet.januaryFirst2022Epoch) diff --git a/DashWallet/Sources/Models/CrowdNode/Services/TransactionObserver.swift b/DashWallet/Sources/Models/CrowdNode/Services/TransactionObserver.swift index b12a4c2a89..79dbfe0d6f 100644 --- a/DashWallet/Sources/Models/CrowdNode/Services/TransactionObserver.swift +++ b/DashWallet/Sources/Models/CrowdNode/Services/TransactionObserver.swift @@ -138,12 +138,76 @@ public final class TransactionObserver { resolved = DispatchQueue.main.sync { MainActor.assumeIsolated { handles() } } } guard let resolved else { return [] } - return scan( + let key = SharedScanKey( + walletId: resolved.walletId, + network: resolved.network, + fetchLimit: fetchLimit, + firstSeenAtOrAfter: firstSeenAtOrAfter) + if let shared = sharedScanResult(for: key) { return shared } + let rows = scan( container: resolved.container, walletId: resolved.walletId, network: resolved.network, fetchLimit: fetchLimit, firstSeenAtOrAfter: firstSeenAtOrAfter) + rememberSharedScan(rows, for: key) + return rows + } + + // MARK: Per-pass scan sharing + + /// Identity of one scan's result: the wallet and network it was read for, + /// plus the arguments that shaped the fetch. + private struct SharedScanKey: Hashable { + let walletId: Data + let network: Network + let fetchLimit: Int? + let firstSeenAtOrAfter: UInt64? + } + + private static let sharedScanLock = NSLock() + private static var sharedScanDepth = 0 + private static var sharedScanResults: [SharedScanKey: [ObservedTransaction]] = [:] + + /// Serves identical `fetchObserved` calls made inside `body` from a single + /// fetch + decode. + /// + /// A CrowdNode restore asks the same question twice — `tryRestoreSignUp` + /// and `getApiAddressConfirmationTx` scan with identical arguments — and + /// on a wallet with thousands of transactions each pass cost ~12s of fetch + /// and decode, paid inline by the caller's thread. + /// + /// Scoped to the call rather than cached across passes on purpose: a row's + /// `context` / `blockHeight` change as it confirms without the row count + /// moving, so a longer-lived memo would answer `isChainAccepted` from + /// stale data. + static func withSharedScan(_ body: () throws -> T) rethrows -> T { + sharedScanLock.lock() + sharedScanDepth += 1 + sharedScanLock.unlock() + defer { + sharedScanLock.lock() + sharedScanDepth -= 1 + if sharedScanDepth == 0 { + sharedScanResults.removeAll() + } + sharedScanLock.unlock() + } + return try body() + } + + private static func sharedScanResult(for key: SharedScanKey) -> [ObservedTransaction]? { + sharedScanLock.lock() + defer { sharedScanLock.unlock() } + guard sharedScanDepth > 0 else { return nil } + return sharedScanResults[key] + } + + private static func rememberSharedScan(_ rows: [ObservedTransaction], for key: SharedScanKey) { + sharedScanLock.lock() + defer { sharedScanLock.unlock() } + guard sharedScanDepth > 0 else { return } + sharedScanResults[key] = rows } /// Total persisted transaction count, or nil when the SDK host has no diff --git a/DashWallet/Sources/UI/Home/Views/HomeViewModel.swift b/DashWallet/Sources/UI/Home/Views/HomeViewModel.swift index c8935b28d1..b3dde0074b 100644 --- a/DashWallet/Sources/UI/Home/Views/HomeViewModel.swift +++ b/DashWallet/Sources/UI/Home/Views/HomeViewModel.swift @@ -65,6 +65,16 @@ class HomeViewModel: ObservableObject { /// Tracks whether initial data load has completed (Fix #2) private var hasCompletedInitialLoad: Bool = false + /// A full reload is running on `queue`. Main-thread-owned: every read and + /// write happens inside `reloadTxDataSource`'s main-actor hop or the + /// completion hop at the end of `performReload`. + private var reloadInFlight = false + + /// A reload was requested while one was already running, so the running + /// pass's snapshot is already stale. Exactly one trailing pass is owed — + /// see `reloadTxDataSource`. + private var reloadRequestedWhileInFlight = false + /// Debounce timer for sync state changes to prevent excessive reloads (Fix #4) private var syncStateDebounceWorkItem: DispatchWorkItem? private let syncStateDebounceInterval: TimeInterval = 0.5 @@ -418,6 +428,21 @@ class HomeViewModel: ObservableObject { // once up front, asynchronously, keeps the pass free-running. let dispatch = { @MainActor [weak self] in guard let self else { return } + // Coalesce, never queue. A pass costs seconds once the wallet has + // a few thousand transactions, while the trigger throttle upstream + // is one second — so enqueueing per trigger let `queue` accumulate + // a backlog that grew for as long as the sync wrote rows, each + // queued pass rebuilding a snapshot the next one already + // superseded. (A restore of a large wallet reached ~3.5 minutes of + // queue latency: the list rendered history that old.) At most one + // pass runs and at most one trailing pass is owed; the trailing + // pass reads the store fresh, so dropping the requests in between + // loses nothing. + guard !self.reloadInFlight else { + self.reloadRequestedWhileInFlight = true + return + } + self.reloadInFlight = true // Pair each request with the filter selection that was live when // it was made. Reading it inside the pass instead would let a pass // triggered by one change render a selection the user made after @@ -591,6 +616,16 @@ class HomeViewModel: ObservableObject { if self.hasMasternodeHistory != hasMasternodes { self.hasMasternodeHistory = hasMasternodes } + + // Release the coalescing gate only after this pass's results are + // on screen, then settle whatever changed while it ran. Ordering + // matters: clearing the request flag before re-entering keeps a + // trigger that lands during the trailing pass from being swallowed. + self.reloadInFlight = false + if self.reloadRequestedWhileInFlight { + self.reloadRequestedWhileInFlight = false + self.reloadTxDataSource() + } } }