|
| 1 | +// |
| 2 | +// CbfClient+Extensions.swift |
| 3 | +// BDKSwiftExampleWallet |
| 4 | +// |
| 5 | +// Created by Matthew Ramsden on 7/30/25. |
| 6 | +// |
| 7 | + |
| 8 | +import BitcoinDevKit |
| 9 | +import Foundation |
| 10 | + |
| 11 | +extension CbfClient { |
| 12 | + // Track monitoring tasks per client for clean cancellation |
| 13 | + private static var monitoringTasks: [ObjectIdentifier: Task<Void, Never>] = [:] |
| 14 | + private static var warningTasks: [ObjectIdentifier: Task<Void, Never>] = [:] |
| 15 | + private static var logTasks: [ObjectIdentifier: Task<Void, Never>] = [:] |
| 16 | + private static var heartbeatTasks: [ObjectIdentifier: Task<Void, Never>] = [:] |
| 17 | + private static var lastInfoAt: [ObjectIdentifier: Date] = [:] |
| 18 | + private static let monitoringTasksQueue = DispatchQueue(label: "cbf.monitoring.tasks") |
| 19 | + |
| 20 | + static func createComponents(wallet: Wallet) -> (client: CbfClient, node: CbfNode) { |
| 21 | + do { |
| 22 | + |
| 23 | + let components = try CbfBuilder() |
| 24 | + .logLevel(logLevel: .debug) |
| 25 | + .scanType(scanType: .sync) |
| 26 | + .dataDir(dataDir: Constants.Config.Kyoto.dbPath) |
| 27 | + .peers(peers: Constants.Networks.Signet.Regular.kyotoPeers) |
| 28 | + .build(wallet: wallet) |
| 29 | + |
| 30 | + components.node.run() |
| 31 | + |
| 32 | + components.client.startBackgroundMonitoring() |
| 33 | + |
| 34 | + return (client: components.client, node: components.node) |
| 35 | + } catch { |
| 36 | + fatalError("Failed to create CBF components: \(error)") |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + func startBackgroundMonitoring() { |
| 41 | + let id = ObjectIdentifier(self) |
| 42 | + |
| 43 | + let task = Task { [self] in |
| 44 | + var hasEstablishedConnection = false |
| 45 | + while true { |
| 46 | + if Task.isCancelled { break } |
| 47 | + do { |
| 48 | + let info = try await self.nextInfo() |
| 49 | + CbfClient.monitoringTasksQueue.sync { Self.lastInfoAt[id] = Date() } |
| 50 | + switch info { |
| 51 | + case let .progress(progress): |
| 52 | + await MainActor.run { |
| 53 | + NotificationCenter.default.post( |
| 54 | + name: NSNotification.Name("KyotoProgressUpdate"), |
| 55 | + object: nil, |
| 56 | + userInfo: ["progress": progress] |
| 57 | + ) |
| 58 | + } |
| 59 | + case let .newChainHeight(height): |
| 60 | + await MainActor.run { |
| 61 | + NotificationCenter.default.post( |
| 62 | + name: NSNotification.Name("KyotoChainHeightUpdate"), |
| 63 | + object: nil, |
| 64 | + userInfo: ["height": height] |
| 65 | + ) |
| 66 | + if !hasEstablishedConnection { |
| 67 | + hasEstablishedConnection = true |
| 68 | + NotificationCenter.default.post( |
| 69 | + name: NSNotification.Name("KyotoConnectionUpdate"), |
| 70 | + object: nil, |
| 71 | + userInfo: ["connected": true] |
| 72 | + ) |
| 73 | + } |
| 74 | + } |
| 75 | + case .connectionsMet, .successfulHandshake: |
| 76 | + await MainActor.run { |
| 77 | + if !hasEstablishedConnection { |
| 78 | + hasEstablishedConnection = true |
| 79 | + NotificationCenter.default.post( |
| 80 | + name: NSNotification.Name("KyotoConnectionUpdate"), |
| 81 | + object: nil, |
| 82 | + userInfo: ["connected": true] |
| 83 | + ) |
| 84 | + } |
| 85 | + } |
| 86 | + default: |
| 87 | + break |
| 88 | + } |
| 89 | + } catch is CancellationError { |
| 90 | + break |
| 91 | + } catch { |
| 92 | + // ignore |
| 93 | + } |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + Self.monitoringTasksQueue.sync { |
| 98 | + Self.monitoringTasks[id] = task |
| 99 | + Self.lastInfoAt[id] = Date() |
| 100 | + } |
| 101 | + |
| 102 | + // Heartbeat task to signal idleness while awaiting Info events |
| 103 | + let heartbeat = Task { |
| 104 | + while true { |
| 105 | + if Task.isCancelled { break } |
| 106 | + try? await Task.sleep(nanoseconds: 5_000_000_000) |
| 107 | + if Task.isCancelled { break } |
| 108 | + var idleFor: TimeInterval = 0 |
| 109 | + CbfClient.monitoringTasksQueue.sync { |
| 110 | + if let last = Self.lastInfoAt[id] { idleFor = Date().timeIntervalSince(last) } |
| 111 | + } |
| 112 | + } |
| 113 | + } |
| 114 | + |
| 115 | + Self.monitoringTasksQueue.sync { |
| 116 | + Self.heartbeatTasks[id] = heartbeat |
| 117 | + } |
| 118 | + |
| 119 | + // Minimal warnings listener for visibility while syncing |
| 120 | + let warnings = Task { [self] in |
| 121 | + while true { |
| 122 | + if Task.isCancelled { break } |
| 123 | + do { |
| 124 | + let warning = try await self.nextWarning() |
| 125 | + if case .needConnections = warning { |
| 126 | + await MainActor.run { |
| 127 | + NotificationCenter.default.post( |
| 128 | + name: NSNotification.Name("KyotoConnectionUpdate"), |
| 129 | + object: nil, |
| 130 | + userInfo: ["connected": false] |
| 131 | + ) |
| 132 | + } |
| 133 | + } |
| 134 | + } catch is CancellationError { |
| 135 | + break |
| 136 | + } catch { |
| 137 | + // ignore |
| 138 | + } |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + Self.monitoringTasksQueue.sync { |
| 143 | + Self.warningTasks[id] = warnings |
| 144 | + } |
| 145 | + |
| 146 | + // Log listener for detailed debugging |
| 147 | + let logs = Task { [self] in |
| 148 | + while true { |
| 149 | + if Task.isCancelled { break } |
| 150 | + do { |
| 151 | + let log = try await self.nextLog() |
| 152 | + } catch is CancellationError { |
| 153 | + break |
| 154 | + } catch { |
| 155 | + // ignore |
| 156 | + } |
| 157 | + } |
| 158 | + } |
| 159 | + |
| 160 | + Self.monitoringTasksQueue.sync { |
| 161 | + Self.logTasks[id] = logs |
| 162 | + } |
| 163 | + } |
| 164 | + |
| 165 | + func stopBackgroundMonitoring() { |
| 166 | + let id = ObjectIdentifier(self) |
| 167 | + Self.monitoringTasksQueue.sync { |
| 168 | + guard let task = Self.monitoringTasks.removeValue(forKey: id) else { return } |
| 169 | + task.cancel() |
| 170 | + if let hb = Self.heartbeatTasks.removeValue(forKey: id) { hb.cancel() } |
| 171 | + if let wt = Self.warningTasks.removeValue(forKey: id) { wt.cancel() } |
| 172 | + if let lt = Self.logTasks.removeValue(forKey: id) { lt.cancel() } |
| 173 | + Self.lastInfoAt.removeValue(forKey: id) |
| 174 | + } |
| 175 | + } |
| 176 | + |
| 177 | + static func cancelAllMonitoring() { |
| 178 | + Self.monitoringTasksQueue.sync { |
| 179 | + for (_, task) in Self.monitoringTasks { task.cancel() } |
| 180 | + for (_, wt) in Self.warningTasks { wt.cancel() } |
| 181 | + for (_, lt) in Self.logTasks { lt.cancel() } |
| 182 | + for (_, hb) in Self.heartbeatTasks { hb.cancel() } |
| 183 | + Self.monitoringTasks.removeAll() |
| 184 | + Self.warningTasks.removeAll() |
| 185 | + Self.logTasks.removeAll() |
| 186 | + Self.heartbeatTasks.removeAll() |
| 187 | + Self.lastInfoAt.removeAll() |
| 188 | + } |
| 189 | + } |
| 190 | +} |
0 commit comments