celestia_rpc/failover.rs
1//! Multi-endpoint Json-RPC client with automatic failover and switch-back.
2//!
3//! [`FailoverClient`] wraps a priority-ordered list of RPC endpoints. Requests
4//! are sent to the most-preferred endpoint that is currently reachable; if a
5//! network error occurs, the client transparently falls back to the next
6//! endpoint. A background health-check task periodically probes the preferred
7//! endpoint and, as soon as it recovers *and its head is recent enough* (within
8//! a configurable max age), switches back to it.
9//!
10//! The actual failover state machine lives in the transport-agnostic
11//! [`lumina_utils::failover::Failover`] engine; this module is the JSON-RPC
12//! adapter around it.
13//!
14//! The first endpoint in the list (index `0`) is the most preferred one.
15//!
16//! # Notes
17//!
18//! - Only *network* errors trigger failover. Server-returned JSON-RPC errors
19//! (e.g. a method returning an error) are returned to the caller as-is and do
20//! not cause a retry on another endpoint.
21//! - Batch requests are routed to the currently selected endpoint without
22//! failover, because [`jsonrpsee`]'s batch builder cannot be replayed.
23//! - For subscriptions, only the initial subscribe call is subject to failover.
24//! If the underlying connection drops mid-stream the subscription ends, and
25//! the caller is expected to re-subscribe (which will pick a healthy endpoint).
26
27use std::fmt;
28use std::sync::Arc;
29use std::time::Duration;
30
31use jsonrpsee::core::ClientError;
32use jsonrpsee::core::JsonRawValue as RawValue;
33use jsonrpsee::core::client::{BatchResponse, ClientT, Subscription, SubscriptionClientT};
34use jsonrpsee::core::params::BatchRequestBuilder;
35use jsonrpsee::core::traits::ToRpcParams;
36use lumina_utils::failover::{Endpoint as FailoverEndpoint, Failover, box_build};
37use serde::de::DeserializeOwned;
38
39use crate::HeaderClient;
40use crate::client::Client;
41use crate::error::Error;
42
43/// Default interval between background health-checks of unhealthy endpoints.
44pub const DEFAULT_HEALTH_CHECK_INTERVAL: Duration = Duration::from_secs(3);
45
46/// Default timeout for a single health-check probe.
47pub const DEFAULT_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
48
49/// Default maximum head age for an endpoint to be considered healthy enough to
50/// switch back to.
51pub const DEFAULT_MAX_HEAD_AGE: Duration = Duration::from_secs(30);
52
53/// A single RPC endpoint with its optional authentication token.
54///
55/// Different providers (e.g. your own node and a fallback such as QuickNode)
56/// commonly require different auth tokens, hence the per-endpoint token.
57#[derive(Debug, Clone)]
58pub struct RpcEndpoint {
59 /// The endpoint url, e.g. `ws://localhost:26658` or `https://rpc.example.com`.
60 pub url: String,
61 /// Optional bearer authentication token for this endpoint.
62 pub auth_token: Option<String>,
63}
64
65impl RpcEndpoint {
66 /// Create a new endpoint from a url, without an auth token.
67 pub fn new(url: impl Into<String>) -> RpcEndpoint {
68 RpcEndpoint {
69 url: url.into(),
70 auth_token: None,
71 }
72 }
73
74 /// Set the authentication token for this endpoint.
75 pub fn auth_token(mut self, token: impl Into<String>) -> RpcEndpoint {
76 self.auth_token = Some(token.into());
77 self
78 }
79}
80
81impl<S> From<S> for RpcEndpoint
82where
83 S: Into<String>,
84{
85 fn from(url: S) -> RpcEndpoint {
86 RpcEndpoint::new(url)
87 }
88}
89
90/// Pre-serialized RPC params, so that a request can be replayed across endpoints.
91///
92/// [`ToRpcParams::to_rpc_params`] consumes its receiver, so to retry the same
93/// request on a different endpoint we serialize the params once up front and
94/// hand out clones.
95struct RawParams(Option<Box<RawValue>>);
96
97impl ToRpcParams for RawParams {
98 fn to_rpc_params(self) -> Result<Option<Box<RawValue>>, serde_json::Error> {
99 Ok(self.0)
100 }
101}
102
103/// A Json-RPC client over multiple endpoints with automatic failover and
104/// switch-back to the preferred endpoint once it recovers.
105///
106/// Requests go to the most-preferred reachable endpoint; on a network error the
107/// client transparently fails over to the next one. When a health-check interval
108/// is configured, a background task switches back to the preferred endpoint once
109/// it recovers and its head is recent enough.
110pub struct FailoverClient {
111 inner: Arc<Failover<Client, ClientError>>,
112}
113
114impl FailoverClient {
115 /// Create a new failover client over the given priority-ordered endpoints.
116 ///
117 /// The first endpoint is the most preferred. When more than one endpoint is
118 /// provided and `health_check_interval` is `Some`, a background task probes
119 /// the preferred endpoint on that interval and switches back to it once it
120 /// recovers.
121 ///
122 /// Endpoint clients are built lazily on first use, so a fallback endpoint
123 /// being unreachable at construction time does not prevent the client from
124 /// being created.
125 pub fn new(
126 endpoints: Vec<RpcEndpoint>,
127 connect_timeout: Option<Duration>,
128 request_timeout: Option<Duration>,
129 health_check_interval: Option<Duration>,
130 max_head_age: Duration,
131 ) -> Result<FailoverClient, Error> {
132 let probe_timeout = request_timeout.unwrap_or(DEFAULT_PROBE_TIMEOUT);
133
134 let slots = endpoints
135 .into_iter()
136 .map(|endpoint| {
137 let url = endpoint.url.clone();
138 FailoverEndpoint::lazy(url, move || {
139 let url = endpoint.url.clone();
140 let auth_token = endpoint.auth_token.clone();
141 box_build(async move {
142 Client::new(
143 &url,
144 auth_token.as_deref(),
145 connect_timeout,
146 request_timeout,
147 )
148 .await
149 .map_err(build_error_to_client_error)
150 })
151 })
152 })
153 .collect::<Vec<_>>();
154
155 let inner = Failover::new(slots, is_network_error, probe_timeout, max_head_age)
156 .ok_or(Error::NoEndpoints)?;
157 let inner = Arc::new(inner);
158
159 if let Some(interval) = health_check_interval {
160 inner.spawn_health_check(interval, |client: Arc<Client>| async move {
161 HeaderClient::header_network_head(client.as_ref())
162 .await
163 .ok()
164 .map(|header| header.time().unix_timestamp())
165 });
166 }
167
168 Ok(FailoverClient { inner })
169 }
170}
171
172/// Returns whether an error should trigger failover to another endpoint.
173///
174/// Only connectivity/transport-level failures count; server-returned JSON-RPC
175/// errors and response parsing errors are treated as real results.
176pub(crate) fn is_network_error(err: &ClientError) -> bool {
177 matches!(
178 err,
179 ClientError::Transport(_)
180 | ClientError::RestartNeeded(_)
181 | ClientError::RequestTimeout
182 | ClientError::ServiceDisconnect
183 | ClientError::Custom(_)
184 )
185}
186
187/// Convert an endpoint-build error into a [`ClientError`], preserving the
188/// underlying jsonrpsee error (e.g. a `Transport` connection failure) where
189/// possible so callers see the same error variant as with a single endpoint.
190fn build_error_to_client_error(err: Error) -> ClientError {
191 match err {
192 Error::JsonRpc(client_err) => client_err,
193 other => ClientError::Custom(other.to_string()),
194 }
195}
196
197impl ClientT for FailoverClient {
198 async fn notification<Params>(&self, method: &str, params: Params) -> Result<(), ClientError>
199 where
200 Params: ToRpcParams + Send,
201 {
202 let raw = params.to_rpc_params()?;
203 self.inner
204 .run(|client| {
205 let raw = raw.clone();
206 async move { client.notification(method, RawParams(raw)).await }
207 })
208 .await
209 }
210
211 async fn request<R, Params>(&self, method: &str, params: Params) -> Result<R, ClientError>
212 where
213 R: DeserializeOwned,
214 Params: ToRpcParams + Send,
215 {
216 let raw = params.to_rpc_params()?;
217 self.inner
218 .run(|client| {
219 let raw = raw.clone();
220 async move { client.request::<R, _>(method, RawParams(raw)).await }
221 })
222 .await
223 }
224
225 async fn batch_request<'a, R>(
226 &self,
227 batch: BatchRequestBuilder<'a>,
228 ) -> Result<BatchResponse<'a, R>, ClientError>
229 where
230 R: DeserializeOwned + fmt::Debug + 'a,
231 {
232 // The batch builder cannot be replayed, so route to the active endpoint
233 // without failover.
234 let client = self.inner.active_client().await?;
235 client.batch_request(batch).await
236 }
237}
238
239impl SubscriptionClientT for FailoverClient {
240 async fn subscribe<'a, N, Params>(
241 &self,
242 subscribe_method: &'a str,
243 params: Params,
244 unsubscribe_method: &'a str,
245 ) -> Result<Subscription<N>, ClientError>
246 where
247 Params: ToRpcParams + Send,
248 N: DeserializeOwned,
249 {
250 let raw = params.to_rpc_params()?;
251 self.inner
252 .run(|client| {
253 let raw = raw.clone();
254 async move {
255 client
256 .subscribe(subscribe_method, RawParams(raw), unsubscribe_method)
257 .await
258 }
259 })
260 .await
261 }
262
263 async fn subscribe_to_method<N>(&self, method: &str) -> Result<Subscription<N>, ClientError>
264 where
265 N: DeserializeOwned,
266 {
267 self.inner
268 .run(|client| async move { client.subscribe_to_method(method).await })
269 .await
270 }
271}
272
273impl fmt::Debug for FailoverClient {
274 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275 f.write_str("FailoverClient { .. }")
276 }
277}
278
279// Integration tests against a live node, mirroring the gRPC failover tests in
280// `celestia-grpc`. The deterministic state-machine coverage lives in the shared
281// engine's unit tests (`lumina_utils::failover`); these check the JSON-RPC
282// adapter end-to-end: requests fail over from an unreachable endpoint to a real
283// one, and exhausting all endpoints surfaces an error.
284#[cfg(all(test, not(target_arch = "wasm32")))]
285mod tests {
286 use super::*;
287 use crate::HeaderClient;
288
289 // An endpoint with nothing listening, so connecting fails fast.
290 const BAD_URL: &str = "ws://localhost:19999";
291 const BAD_URL_2: &str = "ws://localhost:19998";
292
293 /// The live node RPC url, overridable via `CELESTIA_RPC_URL` (node-2, the
294 /// light node, allows unauthenticated header reads).
295 fn celestia_rpc_url() -> String {
296 std::env::var("CELESTIA_RPC_URL").unwrap_or_else(|_| "ws://localhost:46658".to_string())
297 }
298
299 fn failover_client(endpoints: Vec<RpcEndpoint>) -> FailoverClient {
300 FailoverClient::new(endpoints, None, None, None, DEFAULT_MAX_HEAD_AGE).unwrap()
301 }
302
303 #[tokio::test]
304 async fn failover_to_second_endpoint() {
305 // First endpoint is unreachable, should fail over to the second, real one.
306 let client = failover_client(vec![
307 RpcEndpoint::new(BAD_URL),
308 RpcEndpoint::new(celestia_rpc_url()),
309 ]);
310
311 let head = client.header_network_head().await.unwrap();
312 assert!(head.height() > 0);
313 }
314
315 #[tokio::test]
316 async fn endpoint_multiple_requests() {
317 let client = failover_client(vec![
318 RpcEndpoint::new(BAD_URL),
319 RpcEndpoint::new(celestia_rpc_url()),
320 ]);
321
322 for _ in 0..5 {
323 let head = client.header_network_head().await.unwrap();
324 assert!(head.height() > 0);
325 }
326 }
327
328 #[tokio::test]
329 async fn all_endpoints_fail_returns_error() {
330 let client = failover_client(vec![RpcEndpoint::new(BAD_URL), RpcEndpoint::new(BAD_URL_2)]);
331
332 client.header_network_head().await.unwrap_err();
333 }
334
335 /// The live node's `host:port`, derived from [`celestia_rpc_url`].
336 fn celestia_rpc_host_port() -> String {
337 celestia_rpc_url()
338 .trim_start_matches("wss://")
339 .trim_start_matches("ws://")
340 .to_string()
341 }
342
343 /// A controllable TCP proxy placed in front of a real node so a test can
344 /// simulate the upstream disconnecting and recovering.
345 ///
346 /// While enabled it forwards each accepted connection to the upstream. When
347 /// disabled it force-closes live connections and refuses new ones (the ws
348 /// client then sees the connection drop, exactly like a node going away).
349 /// `forwarded` counts the connections it has proxied, so a test can tell
350 /// which endpoint actually served traffic.
351 mod tcp_proxy {
352 use std::net::SocketAddr;
353 use std::sync::Arc;
354 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
355 use std::time::Duration;
356
357 use tokio::net::{TcpListener, TcpStream};
358
359 pub struct TcpProxy {
360 addr: SocketAddr,
361 enabled: Arc<AtomicBool>,
362 forwarded: Arc<AtomicUsize>,
363 }
364
365 impl TcpProxy {
366 pub async fn start(upstream: String) -> TcpProxy {
367 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
368 let addr = listener.local_addr().unwrap();
369 let enabled = Arc::new(AtomicBool::new(true));
370 let forwarded = Arc::new(AtomicUsize::new(0));
371
372 let task_enabled = enabled.clone();
373 let task_forwarded = forwarded.clone();
374 tokio::spawn(async move {
375 loop {
376 let Ok((mut inbound, _)) = listener.accept().await else {
377 break;
378 };
379 if !task_enabled.load(Ordering::SeqCst) {
380 // Refuse: dropping `inbound` closes the connection.
381 continue;
382 }
383 task_forwarded.fetch_add(1, Ordering::SeqCst);
384
385 let conn_enabled = task_enabled.clone();
386 let upstream = upstream.clone();
387 tokio::spawn(async move {
388 let Ok(mut outbound) = TcpStream::connect(&upstream).await else {
389 return;
390 };
391 tokio::select! {
392 _ = tokio::io::copy_bidirectional(&mut inbound, &mut outbound) => {}
393 // Force-close the connection as soon as we're disabled.
394 _ = wait_until_disabled(&conn_enabled) => {}
395 }
396 });
397 }
398 });
399
400 TcpProxy {
401 addr,
402 enabled,
403 forwarded,
404 }
405 }
406
407 pub fn ws_url(&self) -> String {
408 format!("ws://{}", self.addr)
409 }
410
411 pub fn disable(&self) {
412 self.enabled.store(false, Ordering::SeqCst);
413 }
414
415 pub fn enable(&self) {
416 self.enabled.store(true, Ordering::SeqCst);
417 }
418
419 pub fn forwarded(&self) -> usize {
420 self.forwarded.load(Ordering::SeqCst)
421 }
422 }
423
424 async fn wait_until_disabled(enabled: &AtomicBool) {
425 while enabled.load(Ordering::SeqCst) {
426 tokio::time::sleep(Duration::from_millis(20)).await;
427 }
428 }
429 }
430
431 /// End-to-end against a real node: the preferred endpoint goes through a
432 /// controllable TCP proxy, the fallback is the node directly. Killing the
433 /// proxy drops the preferred connection (→ fail over); restoring it must let
434 /// the background health-check reconnect through the *same cached* client and
435 /// route traffic back to the preferred endpoint.
436 ///
437 /// `WsReconnectClient` keeps a single persistent connection, so the proxy's
438 /// per-connection counter rising again is exactly the signal that the cached
439 /// client reconnected after the drop. We use a generous `max_head_age` so the
440 /// switch-back tests the reconnect path rather than chain liveness (a static
441 /// devnet may have a stale head).
442 #[tokio::test]
443 async fn switches_back_to_preferred_after_reconnect() {
444 use std::time::Duration;
445
446 // Large enough that a reachable-but-not-advancing devnet still counts as
447 // fresh; this test is about reconnect/switch-back, not head freshness.
448 let max_head_age = Duration::from_secs(3600 * 24 * 365 * 10);
449
450 let proxy = tcp_proxy::TcpProxy::start(celestia_rpc_host_port()).await;
451
452 let client = FailoverClient::new(
453 vec![
454 RpcEndpoint::new(proxy.ws_url()),
455 RpcEndpoint::new(celestia_rpc_url()),
456 ],
457 None,
458 None,
459 // Fast health-check so the test doesn't wait long for switch-back.
460 Some(Duration::from_millis(500)),
461 max_head_age,
462 )
463 .unwrap();
464
465 // Preferred (through the proxy) serves the first request, opening one
466 // connection.
467 client.header_network_head().await.unwrap();
468 assert_eq!(
469 proxy.forwarded(),
470 1,
471 "preferred endpoint should serve first"
472 );
473
474 // Kill the preferred: force-close its connection and refuse new ones. Give
475 // the force-close a moment to land, then a request must fail over to the
476 // fallback (real node) and succeed.
477 proxy.disable();
478 tokio::time::sleep(Duration::from_millis(250)).await;
479 let head = client.header_network_head().await.unwrap();
480 assert!(
481 head.height() > 0,
482 "fallback should serve while preferred is down"
483 );
484
485 // The preferred is now unhealthy and its connection is gone; the counter
486 // is stable while disabled.
487 let before = proxy.forwarded();
488
489 // Restore the preferred. The background health-check reuses the SAME cached
490 // client, which reconnects (a new proxied connection → counter rises) and
491 // is marked healthy again, so routing returns to the preferred endpoint.
492 proxy.enable();
493 let mut switched_back = false;
494 for _ in 0..40 {
495 tokio::time::sleep(Duration::from_millis(300)).await;
496 client.header_network_head().await.unwrap();
497 if proxy.forwarded() > before {
498 switched_back = true;
499 break;
500 }
501 }
502 assert!(
503 switched_back,
504 "should reconnect and route back through the preferred endpoint after it recovers"
505 );
506 }
507}