diff --git a/Bitkit.xcodeproj/project.pbxproj b/Bitkit.xcodeproj/project.pbxproj index df9571d4a..7dbe440ca 100644 --- a/Bitkit.xcodeproj/project.pbxproj +++ b/Bitkit.xcodeproj/project.pbxproj @@ -1295,7 +1295,7 @@ repositoryURL = "https://github.com/synonymdev/ldk-node"; requirement = { kind = exactVersion; - version = "0.7.0-rc.81"; + version = "0.7.0-rc.82"; }; }; 96DEA0382DE8BBA1009932BF /* XCRemoteSwiftPackageReference "bitkit-core" */ = { diff --git a/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 879f7e42c..b4553c9dd 100644 --- a/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -24,8 +24,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/synonymdev/ldk-node", "state" : { - "revision" : "366d56ef3c735406146ed12a34aba291776d29f6", - "version" : "0.7.0-rc.81" + "revision" : "1dd2f42e44561ee4005f109c0d2cb61e1de99123", + "version" : "0.7.0-rc.82" } }, { diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 9b6158e9a..8d262df86 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -158,6 +158,10 @@ class LightningService: NodeLifecycleService { private let restartLock = NSLock() private var lastRestart: Task? + /// Counts the stops callers asked for, so a recovery start can tell that one came in after it began. + private var requestedStops = 0 + /// Starts while a stopped node's VSS writes keep the store busy; each build waits up to 60 s for them. + static let busyStoreStartAttempts = 5 private let eventLoopLock = NSLock() /// The current event loop and the node it serves, so only that node's lifecycle can cancel it. @@ -435,42 +439,56 @@ class LightningService: NodeLifecycleService { // Stop the current node if it exists, ignore errors if already stopped if let node { do { - try await stop() + try await stopNode() } catch { Logger.debug("Node was already stopped or failed to stop: \(error)") // Clear the node reference anyway await releaseAfterFailedStop(of: node) } } + let stopsBefore = restartLock.withLock { requestedStops } - // Restart the node with the current configuration + try await Self.applyConfigChange( + stopRequested: { self.restartLock.withLock { self.requestedStops != stopsBefore } }, + start: { + try await self.setup(walletIndex: self.currentWalletIndex, electrumServerUrl: electrumServerUrl, rgsServerUrl: rgsServerUrl) + try await self.start() + }, + recover: { try await self.restartWithPreviousConfig(stopsBefore: stopsBefore) } + ) + } + + /// Starts the node with a changed config, retrying while the store is busy with the stopped node's VSS writes, which have + /// nothing to do with the new config. Any other failure, or a busy store past every attempt, runs `recover` and rethrows. + static func applyConfigChange( + stopRequested: () -> Bool, + start: () async throws -> Void, + recover: () async throws -> Void + ) async throws { do { - try await setup(walletIndex: currentWalletIndex, electrumServerUrl: electrumServerUrl, rgsServerUrl: rgsServerUrl) - try await start() - Logger.info("Node restarted successfully") + try await startRetryingBusyStore(stopRequested: stopRequested, start: start) + Logger.info("Node restarted successfully", context: "LightningService") } catch { - Logger.warn("Failed ldk-node config change, attempting recovery…") - // Attempt to restart with previous config + Logger.warn("Failed ldk-node config change, attempting recovery…", context: "LightningService") // If recovery fails, log it but still throw the original error do { - try await restartWithPreviousConfig() + try await recover() } catch { - Logger.error("Recovery attempt also failed: \(error)") + Logger.error("Recovery attempt also failed: \(error)", context: "LightningService") } - // Always re-throw the original error that caused the restart failure throw error } } /// Restarts the node with the previous stored configuration (recovery method) /// This is called when a config change fails to restore the node to a working state - private func restartWithPreviousConfig() async throws { + private func restartWithPreviousConfig(stopsBefore: Int) async throws { Logger.debug("Stopping node for recovery attempt") // Stop the current node if it exists if let node { do { - try await stop() + try await stopNode() } catch { Logger.error("Failed to stop node during recovery: \(error)") await releaseAfterFailedStop(of: node) @@ -480,9 +498,12 @@ class LightningService: NodeLifecycleService { Logger.debug("Starting node with previous config for recovery") do { - // Restart with nil URLs to use stored/default configuration - try await setup(walletIndex: currentWalletIndex, electrumServerUrl: nil, rgsServerUrl: nil) - try await start() + // The stopped node's VSS writes can keep retrying for minutes, past one build's wait for them. + try await Self.startRetryingBusyStore(stopRequested: { self.restartLock.withLock { self.requestedStops != stopsBefore } }) { + // Restart with nil URLs to use stored/default configuration + try await self.setup(walletIndex: self.currentWalletIndex, electrumServerUrl: nil, rgsServerUrl: nil) + try await self.start() + } Logger.debug("Successfully started node with previous config") } catch { Logger.error("Failed starting node with previous config: \(error)") @@ -490,6 +511,40 @@ class LightningService: NodeLifecycleService { } } + /// Runs `start` again while it fails because the store is still busy with a stopped node's VSS writes, up to + /// `busyStoreStartAttempts` times. A stop requested meanwhile wins: no further start runs. + static func startRetryingBusyStore( + attempts: Int = busyStoreStartAttempts, + stopRequested: () -> Bool, + start: () async throws -> Void + ) async throws { + var attempt = 0 + while true { + guard !stopRequested() else { + Logger.info("Skipped node start because a stop was requested", context: "LightningService") + throw AppError(serviceError: .nodeNotSetup) + } + attempt += 1 + if attempt > 1 { + Logger.warn("Retrying node start on a busy store '\(attempt)/\(attempts)'", context: "LightningService") + } + do { + try await start() + return + } catch where isKvStoreSetupFailure(error) && attempt < attempts { + continue + } + } + } + + static func isKvStoreSetupFailure(_ error: Error) -> Bool { + let underlying = (error as? AppError)?.underlyingError ?? error + if case BuildError.KvStoreSetupFailed = underlying { + return true + } + return false + } + /// Pass onEvent when being used in the background to listen for payments, channels, closes, etc /// - Parameter onEvent: Triggered on any LDK node event func start(onEvent: ((Event) -> Void)? = nil) async throws { @@ -550,6 +605,12 @@ class LightningService: NodeLifecycleService { } func stop(clearEventCallback: Bool = false) async throws { + restartLock.withLock { requestedStops += 1 } + try await stopNode(clearEventCallback: clearEventCallback) + } + + /// Stops the node without counting as a requested stop, for the restart and its recovery. + private func stopNode(clearEventCallback: Bool = false) async throws { guard let node else { Logger.warn("Node not started, nothing to stop") return diff --git a/BitkitTests/LightningServiceTests.swift b/BitkitTests/LightningServiceTests.swift index 20b5db00a..3341a37d7 100644 --- a/BitkitTests/LightningServiceTests.swift +++ b/BitkitTests/LightningServiceTests.swift @@ -61,4 +61,103 @@ final class LightningServiceTests: XCTestCase { release.continuation.finish() await task.value } + + // Regression: a stopped node's VSS writes can keep retrying past one build's wait for them, so the recovery start + // retries while the build fails on the busy store instead of leaving the node offline. + func testRecoveryStartRetriesWhileTheVssStoreIsBusy() async throws { + let busy = Bitkit.AppError(error: BuildError.KvStoreSetupFailed(message: "in flight")) + var attempts = 0 + try await Bitkit.LightningService.startRetryingBusyStore(stopRequested: { false }) { + attempts += 1 + if attempts < 3 { + throw busy + } + } + XCTAssertEqual(attempts, 3) + } + + func testRecoveryStartGivesUpAfterItsAttempts() async { + var attempts = 0 + do { + try await Bitkit.LightningService.startRetryingBusyStore(stopRequested: { false }) { + attempts += 1 + throw Bitkit.AppError(error: BuildError.KvStoreSetupFailed(message: "in flight")) + } + XCTFail("expected the last failure") + } catch {} + XCTAssertEqual(attempts, Bitkit.LightningService.busyStoreStartAttempts) + } + + func testRecoveryStartDoesNotRetryOtherFailures() async { + var attempts = 0 + do { + try await Bitkit.LightningService.startRetryingBusyStore(stopRequested: { false }) { + attempts += 1 + throw Bitkit.AppError(error: BuildError.WalletSetupFailed(message: "")) + } + XCTFail("expected the failure") + } catch {} + XCTAssertEqual(attempts, 1) + } + + // Regression: a stop requested while the recovery runs wins over its retry. + func testRecoveryStartDoesNotRetryOverARequestedStop() async { + var attempts = 0 + var stopRequested = false + do { + try await Bitkit.LightningService.startRetryingBusyStore(stopRequested: { stopRequested }) { + attempts += 1 + stopRequested = true + throw Bitkit.AppError(error: BuildError.KvStoreSetupFailed(message: "in flight")) + } + XCTFail("expected the skipped start to fail") + } catch {} + XCTAssertEqual(attempts, 1) + } + + func testRecoveryStartDoesNotStartOverAStopRequestedBeforeIt() async { + var attempts = 0 + do { + try await Bitkit.LightningService.startRetryingBusyStore(stopRequested: { true }) { attempts += 1 } + XCTFail("expected the skipped start to fail") + } catch {} + XCTAssertEqual(attempts, 0) + } + + // Regression: a busy store has nothing to do with the requested Electrum or RGS server, so the change retries it + // instead of falling back to the previous config. + func testConfigChangeRetriesItsOwnStartWhileTheVssStoreIsBusy() async throws { + var attempts = 0 + var recovered = false + try await Bitkit.LightningService.applyConfigChange( + stopRequested: { false }, + start: { + attempts += 1 + if attempts < 2 { + throw Bitkit.AppError(error: BuildError.KvStoreSetupFailed(message: "in flight")) + } + }, + recover: { recovered = true } + ) + XCTAssertEqual(attempts, 2) + XCTAssertFalse(recovered) + } + + func testConfigChangeRecoversAfterAnotherFailure() async { + var attempts = 0 + var recovered = false + do { + try await Bitkit.LightningService.applyConfigChange( + stopRequested: { false }, + start: { + attempts += 1 + throw Bitkit.AppError(error: BuildError.WalletSetupFailed(message: "")) + }, + recover: { recovered = true } + ) + XCTFail("expected the change to fail") + } catch {} + XCTAssertEqual(attempts, 1) + XCTAssertTrue(recovered) + } } diff --git a/changelog.d/next/1520.fixed.md b/changelog.d/next/1520.fixed.md new file mode 100644 index 000000000..45ee7f9fe --- /dev/null +++ b/changelog.d/next/1520.fixed.md @@ -0,0 +1 @@ +Fixed a rare case where restarting the Lightning node could overwrite its newer backed-up state with older data.