From e36d3477198fe1b736d1bba7e293f48a23b13a67 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 1 Dec 2026 13:48:16 +0100 Subject: [PATCH] fix: reuse the read connection for vss writes Since 0.7.0-rc.82 writes went through their own VssClients, each with a new reqwest client, so the first write after a node build opened a new connection instead of reusing the one the reads had just opened. On a phone that put a DNS lookup, TCP connect and TLS handshake, and any retries of a failing connect, into the first channel monitor write while the node builds. Each side's read and write clients now share one reqwest client, built with the timeouts VssClient::new_with_headers uses. Write retries stay in fenced_retry. Verified: cargo test --lib vss_store (the new connection test fails on main with 2 connections); staging VSS through a local proxy adding 2 s per new connection: the first sync monitor write takes 0.38 s, against 2.33-2.41 s on rc.84 and 0.21-0.37 s on rc.80 --- CHANGELOG.md | 1 + src/io/vss_store.rs | 128 ++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 124 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cc0a33db89..b033896082 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Bug Fixes +- Fixed slow node starts on mobile networks since 0.7.0-rc.82: VSS writes reuse the connection the store's reads opened instead of opening a new one. - A panic in the mobile bindings no longer aborts the app: exports return an error, every running node stops processing and persisting, and a node built before the panic fails to start with `PersistenceFailed`, so build a new one. - Prevent writes of a stopped node, still retrying against VSS or started by its detached work, from overwriting the state of a node rebuilt on the same store: building a VSS store now waits for a node still running on the same store and wallet to stop and for its writes, retries included, to return, fails with `KVStoreSetupFailed` without replacing anything if they have not after 60 s, and otherwise drops the earlier store's writes from then on, failing all but channel monitor writes; a node whose store has been replaced fails to start with `PersistenceFailed`. - Prevent the native SIGABRT `A Tokio 1.x context was found, but it is being shutdown.` when a node is released while background work is still stuck, e.g. in a VSS write after a timed-out stop: the runtime is now kept alive until that work ends instead of being shut down under it. diff --git a/src/io/vss_store.rs b/src/io/vss_store.rs index 5461d2cfdc..a3eb34e1b8 100644 --- a/src/io/vss_store.rs +++ b/src/io/vss_store.rs @@ -313,9 +313,15 @@ impl VssStore { let internal_runtime = Arc::new(StoreRuntime::new("ldk-node-vss-runtime", INTERNAL_RUNTIME_WORKERS, "VSS")?); + // Writes share each side's HTTP client with its reads, so the first write reuses the + // connection the reads opened instead of connecting anew. + let blocking_http_client = build_http_client()?; + let async_http_client = build_http_client()?; + let sync_retry_policy = retry_policy(); - let blocking_client = VssClient::new_with_headers( + let blocking_client = VssClient::from_client_and_headers( base_url.clone(), + blocking_http_client.clone(), sync_retry_policy, header_provider.clone(), ); @@ -338,20 +344,26 @@ impl VssStore { } let async_retry_policy = retry_policy(); - let async_client = VssClient::new_with_headers( + let async_client = VssClient::from_client_and_headers( base_url.clone(), + async_http_client.clone(), async_retry_policy, header_provider.clone(), ); // Writes retry in `fenced_retry`, which bounds each attempt; each call counts in flight from // `StoreFence::begin_write` at its call site. - let blocking_write_client = VssClient::new_with_headers( + let blocking_write_client = VssClient::from_client_and_headers( base_url.clone(), + blocking_http_client, no_retry_policy(), header_provider.clone(), ); - let async_write_client = - VssClient::new_with_headers(base_url, no_retry_policy(), header_provider); + let async_write_client = VssClient::from_client_and_headers( + base_url, + async_http_client, + no_retry_policy(), + header_provider, + ); let inner = Arc::new(VssStoreInner::new( schema_version, @@ -1020,6 +1032,18 @@ fn fence_url(base_url: &str) -> String { url.trim_end_matches('/').to_string() } +// The timeouts `VssClient::new_with_headers` gives its own HTTP client. +const HTTP_TIMEOUT: Duration = Duration::from_secs(10); + +fn build_http_client() -> io::Result { + reqwest::Client::builder() + .timeout(HTTP_TIMEOUT) + .connect_timeout(HTTP_TIMEOUT) + .read_timeout(HTTP_TIMEOUT) + .build() + .map_err(|e| Error::new(ErrorKind::Other, format!("Failed to build VSS HTTP client: {e}"))) +} + fn retry_policy() -> CustomRetryPolicy { ExponentialBackoffRetryPolicy::new(Duration::from_millis(10)) .with_max_attempts(100) @@ -1655,3 +1679,97 @@ mod tests { assert_eq!(KVStoreSync::read(¤t, monitors, "", "monitor").unwrap(), vec![2]); } } + +#[cfg(test)] +mod connection_tests { + use std::io::{BufRead, BufReader, Read, Write}; + use std::net::TcpListener; + use std::sync::atomic::AtomicUsize; + + use vss_client::headers::FixedHeaders; + use vss_client::types::{ErrorCode, ErrorResponse, ListKeyVersionsResponse}; + + use super::*; + + /// Serves an empty VSS store over plain HTTP and counts the connections it accepts. + fn serve_empty_store() -> (String, Arc) { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let connections = Arc::new(AtomicUsize::new(0)); + let counted = Arc::clone(&connections); + std::thread::spawn(move || { + for stream in listener.incoming() { + let stream = stream.unwrap(); + counted.fetch_add(1, Ordering::SeqCst); + std::thread::spawn(move || serve_connection(stream)); + } + }); + (url, connections) + } + + fn serve_connection(stream: std::net::TcpStream) { + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut stream = stream; + loop { + let mut request_line = String::new(); + if reader.read_line(&mut request_line).unwrap_or(0) == 0 { + return; + } + let mut content_length = 0; + loop { + let mut header = String::new(); + if reader.read_line(&mut header).unwrap_or(0) == 0 { + return; + } + if header == "\r\n" { + break; + } + if let Some(value) = header.to_ascii_lowercase().strip_prefix("content-length:") { + content_length = value.trim().parse().unwrap(); + } + } + let mut body = vec![0; content_length]; + reader.read_exact(&mut body).unwrap(); + + let (status, response) = if request_line.contains("/getObject") { + let error = ErrorResponse { + error_code: ErrorCode::NoSuchKeyException.into(), + message: String::new(), + }; + ("404 Not Found", error.encode_to_vec()) + } else if request_line.contains("/listKeyVersions") { + let list = ListKeyVersionsResponse { + key_versions: vec![], + next_page_token: Some(String::new()), + global_version: None, + }; + ("200 OK", list.encode_to_vec()) + } else { + ("200 OK", vec![]) + }; + let head = format!("HTTP/1.1 {}\r\nContent-Length: {}\r\n\r\n", status, response.len()); + stream.write_all(head.as_bytes()).unwrap(); + stream.write_all(&response).unwrap(); + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 1)] + async fn first_write_reuses_the_read_connection() { + let (url, connections) = serve_empty_store(); + let mut vss_seed = [0u8; 32]; + rand::rng().fill_bytes(&mut vss_seed); + let headers = Arc::new(FixedHeaders::new(HashMap::new())); + let logger = Arc::new(Logger::new_log_facade()); + let store = VssStore::new(url, "store".to_string(), vss_seed, headers, logger).unwrap(); + assert_eq!(connections.load(Ordering::SeqCst), 1); + + KVStoreSync::write(&store, "monitors", "", "monitor", vec![1]).unwrap(); + assert_eq!(connections.load(Ordering::SeqCst), 1); + + // The async side keeps its own connection, which its writes reuse too. + KVStore::read(&store, "monitors", "", "missing").await.unwrap_err(); + assert_eq!(connections.load(Ordering::SeqCst), 2); + KVStore::write(&store, "monitors", "", "monitor", vec![2]).await.unwrap(); + assert_eq!(connections.load(Ordering::SeqCst), 2); + } +}