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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
128 changes: 123 additions & 5 deletions src/io/vss_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
);
Expand All @@ -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,
Expand Down Expand Up @@ -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> {
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)
Expand Down Expand Up @@ -1655,3 +1679,97 @@ mod tests {
assert_eq!(KVStoreSync::read(&current, 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<AtomicUsize>) {
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);
}
}
Loading