sui_rpc/client/mod.rs
1use std::sync::Arc;
2use std::time::Duration;
3use tap::Pipe;
4use tonic::body::Body;
5use tonic::codec::CompressionEncoding;
6use tonic::transport::channel::ClientTlsConfig;
7use tower::Layer;
8use tower::Service;
9use tower::ServiceBuilder;
10use tower::util::BoxLayer;
11use tower::util::BoxService;
12
13mod response_ext;
14pub use response_ext::ResponseExt;
15
16mod interceptors;
17pub use interceptors::HeadersInterceptor;
18
19mod watchdog;
20pub use watchdog::BodyIdleTimeout;
21use watchdog::DEFAULT_BODY_IDLE_TIMEOUT;
22use watchdog::WatchdogLayer;
23
24mod unsent_request_retry;
25use unsent_request_retry::UnsentRequestRetry;
26
27mod staking_rewards;
28pub use staking_rewards::DelegatedStake;
29
30mod coin_selection;
31mod ledger_streams;
32mod lists;
33pub use ledger_streams::CheckpointStreamFrame;
34pub use ledger_streams::CheckpointStreamRequest;
35pub use ledger_streams::CheckpointStreamStart;
36pub use ledger_streams::Delivery;
37pub use ledger_streams::EventStreamFrame;
38pub use ledger_streams::EventStreamRequest;
39pub use ledger_streams::EventStreamStart;
40pub use ledger_streams::LedgerStreamConfig;
41pub use ledger_streams::LedgerStreamEvent;
42pub use ledger_streams::LedgerStreamFamily;
43pub use ledger_streams::LedgerStreamOperation;
44pub use ledger_streams::LedgerStreamStage;
45pub use ledger_streams::ListConfig;
46pub use ledger_streams::ListEvent;
47pub use ledger_streams::Position;
48pub use ledger_streams::TransactionStreamFrame;
49pub use ledger_streams::TransactionStreamRequest;
50pub use ledger_streams::TransactionStreamStart;
51
52mod transaction_execution;
53pub use transaction_execution::ExecuteAndWaitError;
54
55use crate::proto::sui::rpc::v2::ledger_service_client::LedgerServiceClient;
56use crate::proto::sui::rpc::v2::move_package_service_client::MovePackageServiceClient;
57use crate::proto::sui::rpc::v2::signature_verification_service_client::SignatureVerificationServiceClient;
58use crate::proto::sui::rpc::v2::state_service_client::StateServiceClient;
59use crate::proto::sui::rpc::v2::subscription_service_client::SubscriptionServiceClient;
60use crate::proto::sui::rpc::v2::transaction_execution_service_client::TransactionExecutionServiceClient;
61#[cfg(feature = "unstable")]
62use crate::proto::sui::rpc::v2alpha::proof_service_client::ProofServiceClient;
63
64type Result<T, E = tonic::Status> = std::result::Result<T, E>;
65type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
66type BoxedChannel = BoxService<http::Request<Body>, http::Response<Body>, tonic::Status>;
67
68type RequestLayer = BoxLayer<
69 BoxService<http::Request<Body>, http::Response<Body>, BoxError>,
70 http::Request<Body>,
71 http::Response<Body>,
72 BoxError,
73>;
74
75const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
76const DEFAULT_TCP_KEEPALIVE_IDLE: Duration = Duration::from_secs(15);
77const DEFAULT_TCP_KEEPALIVE_INTERVAL: Duration = Duration::from_secs(5);
78const DEFAULT_TCP_KEEPALIVE_RETRIES: u32 = 3;
79const DEFAULT_HTTP2_KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(5);
80const DEFAULT_HTTP2_KEEP_ALIVE_TIMEOUT: Duration = Duration::from_secs(20);
81const DEFAULT_NUM_CONNECTIONS: usize = 1;
82
83// RPCs made through a `Client` (and all of its clones) are multiplexed over
84// its HTTP/2 connections, so each connection-level receive window is shared
85// by every in-flight response on that connection. A streaming response that the
86// application holds without polling pins up to a full stream window of that
87// shared budget; once the connection window is exhausted, every RPC on the
88// channel hangs indefinitely while TCP and HTTP/2 keepalives stay healthy.
89// hyper's client defaults (2 MiB stream / 5 MiB connection) let ~3 stalled
90// streams starve the connection. Keep the stream window at hyper's default
91// but raise the connection window so ~32 concurrently stalled streams are
92// needed instead.
93const DEFAULT_HTTP2_STREAM_WINDOW_SIZE: u32 = 2 * 1024 * 1024;
94const DEFAULT_HTTP2_CONNECTION_WINDOW_SIZE: u32 = 64 * 1024 * 1024;
95
96/// A gRPC client for the Sui fullnode RPC interface.
97///
98/// RPCs made through a client and its clones are multiplexed over a single
99/// HTTP/2 connection by default; see
100/// [`with_num_connections`](Client::with_num_connections) to spread them over
101/// several.
102///
103/// # Ledger streams
104///
105/// `Client` provides two styles of stream operations for checkpoints, transactions, and events:
106///
107/// - `list_*` ([`list_checkpoints`](Client::list_checkpoints), [`list_transactions`](Client::list_transactions), [`list_events`](Client::list_events)):
108/// Finite pagination streams yielding raw response pages until reaching an end bound or the ledger tip.
109/// - `stream_*` ([`stream_checkpoints`](Client::stream_checkpoints), [`stream_transactions`](Client::stream_transactions), [`stream_events`](Client::stream_events)):
110/// Resumable, infinite streams starting from any position (`Tip`, `Checkpoint`, or `ResumeAt`
111/// from a frame) that automatically handle backfill replay, live subscription or polling, and
112/// transient error retries.
113///
114/// Streams order and deduplicate frames by each watermark's `cursor_position`; a frame without it,
115/// as servers that predate cursor positions send, ends the stream with `DataLoss`.
116///
117/// Process a payload before persisting its restart position. To resume after a checkpoint, pass
118/// `cursor + 1` to [`CheckpointStreamStart::Checkpoint`]. To resume transactions or events, pass
119/// `frame.cursor` and `frame.position` to [`TransactionStreamStart::ResumeAt`] or
120/// [`EventStreamStart::ResumeAt`].
121///
122/// ## Example
123///
124/// ```no_run
125/// # use futures::StreamExt;
126/// # use sui_rpc::field::{FieldMask, FieldMaskUtil};
127/// # use sui_rpc::proto::sui::rpc::v2::ExecutedTransaction;
128/// # use sui_rpc::Client;
129/// # use sui_rpc::client::{Position, TransactionStreamRequest, TransactionStreamStart};
130/// # use prost::bytes::Bytes;
131/// #
132/// # async fn process_transaction(_: &ExecutedTransaction) {}
133/// # async fn persist_position(_: &Bytes, _: Position) {}
134/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
135/// let client = Client::new(Client::MAINNET_FULLNODE)?;
136/// let read_mask = FieldMask::from_paths(["digest"]);
137/// let request = TransactionStreamRequest::new().with_read_mask(read_mask.clone());
138///
139/// let mut stream = Box::pin(client.stream_transactions(request));
140/// let (cursor, position) = loop {
141/// let Some(frame) = stream.next().await else {
142/// return Ok(());
143/// };
144/// let frame = frame?;
145///
146/// if let Some(transaction) = &frame.transaction {
147/// process_transaction(transaction).await;
148/// }
149/// persist_position(&frame.cursor, frame.position).await;
150/// break (frame.cursor, frame.position);
151/// };
152/// drop(stream);
153///
154/// let restart_request = TransactionStreamRequest::new()
155/// .with_read_mask(read_mask)
156/// .with_start(TransactionStreamStart::ResumeAt { cursor, position });
157/// let mut resumed = Box::pin(client.stream_transactions(restart_request));
158/// let _ = resumed.next().await;
159/// # Ok(())
160/// # }
161/// ```
162///
163/// # Timeouts and deadlines
164///
165/// No default bounds the total duration of a call. Two opt-in bounds are
166/// available:
167///
168/// - A per-call deadline set with [`tonic::Request::set_timeout`]. This
169/// attaches the standard `grpc-timeout` header, so a server that supports
170/// it enforces the deadline too, and the client enforces it locally end to
171/// end: tonic bounds the wait for response headers, and the client's
172/// watchdog (see [`with_body_idle_timeout`](Client::with_body_idle_timeout))
173/// bounds the response body against the same deadline.
174/// The ledger-stream `list_*` and `stream_*` methods do not accept
175/// `tonic::Request`. One logical operation may issue several RPCs, so per-RPC
176/// authentication, common headers, tracing, and timeouts belong on the
177/// client: static headers on [`Client::with_headers`], dynamic per-RPC auth
178/// or tracing on [`Client::request_layer`]. Configuring a [`Clone`]d client
179/// affects only that clone and shares the underlying connection, so a single
180/// stream gets dedicated headers by receiving a configured clone.
181/// - A client-wide response-headers timeout set with
182/// [`with_response_headers_timeout`](Client::with_response_headers_timeout).
183/// This is enforced locally only and its timer stops once response headers
184/// arrive, so it bounds every unary call (whose headers are not sent until
185/// the handler completes) without cutting off long-lived streams.
186///
187/// Independent of any deadline, the watchdog resets RPCs whose response body
188/// makes no progress for 30 seconds (configurable), so a call on a stalled
189/// connection fails with `DeadlineExceeded` instead of hanging forever.
190///
191/// # Undelivered requests
192///
193/// Requests the server never processed are resent automatically, following
194/// gRPC's transparent retry (gRFC A6) as grpc-go and grpc-java implement it:
195/// a request cancelled before it left the client is retried up to three
196/// times, and a request the server rejected unprocessed -- a stream above the
197/// last stream id of a NO_ERROR GOAWAY, as sent when a server or load
198/// balancer drains a connection, or a stream reset with REFUSED_STREAM -- is
199/// retried once. A request the server may have processed is never resent.
200/// A per-call deadline ([`tonic::Request::set_timeout`]) covers all attempts
201/// together; the response-headers timeout applies to each attempt.
202#[derive(Clone)]
203pub struct Client {
204 channel: tonic::transport::Channel,
205
206 // Everything other than the channel is only consulted when building a
207 // per-service client or reconfiguring, so it lives behind an `Arc` to
208 // keep `Client` itself small; it is cloned by value into futures
209 // throughout the SDK. The `Endpoint` alone is over 500 bytes.
210 config: Arc<ClientConfig>,
211}
212
213#[derive(Clone)]
214struct ClientConfig {
215 uri: http::Uri,
216 endpoint: tonic::transport::Endpoint,
217 headers: HeadersInterceptor,
218 max_decoding_message_size: Option<usize>,
219 body_idle_timeout: Option<Duration>,
220 num_connections: usize,
221
222 /// Layer to apply to all RPC requests
223 request_layer: Option<RequestLayer>,
224}
225
226/// Open `num_connections` lazy connections to `endpoint`, all sharing its
227/// configuration, and balance requests across them.
228///
229/// Each connection is inserted under its own key, because the balancer
230/// identifies backends by key and the endpoint is the same for all of them.
231/// The change sender is dropped once the set is populated: the set is fixed,
232/// and the balancer retains it after discovery ends.
233fn build_channel(
234 endpoint: &tonic::transport::Endpoint,
235 num_connections: usize,
236) -> tonic::transport::Channel {
237 if num_connections <= 1 {
238 return endpoint.connect_lazy();
239 }
240
241 let (channel, changes) = tonic::transport::Channel::balance_channel::<usize>(num_connections);
242 for key in 0..num_connections {
243 changes
244 .try_send(tonic::transport::channel::Change::Insert(
245 key,
246 endpoint.clone(),
247 ))
248 .expect("change channel has capacity for every connection");
249 }
250
251 channel
252}
253
254impl Client {
255 /// URL for the public-good, Sui Foundation provided fullnodes for mainnet.
256 pub const MAINNET_FULLNODE: &str = "https://fullnode.mainnet.sui.io";
257
258 /// URL for the public-good, Sui Foundation provided fullnodes for testnet.
259 pub const TESTNET_FULLNODE: &str = "https://fullnode.testnet.sui.io";
260
261 /// URL for the public-good, Sui Foundation provided fullnodes for devnet.
262 pub const DEVNET_FULLNODE: &str = "https://fullnode.devnet.sui.io";
263
264 /// URL for the public-good, Sui Foundation provided archive for mainnet.
265 pub const MAINNET_ARCHIVE: &str = "https://archive.mainnet.sui.io";
266
267 /// URL for the public-good, Sui Foundation provided archive for testnet.
268 pub const TESTNET_ARCHIVE: &str = "https://archive.testnet.sui.io";
269
270 /// Build a client from a fully custom [`tonic::transport::Endpoint`].
271 ///
272 /// This bypasses every transport default that [`Client::new`] applies,
273 /// including the HTTP/2 flow-control windows that protect a connection
274 /// from starvation by stalled streaming responses. Prefer
275 /// [`Client::new`] plus the `with_*` configuration methods unless an
276 /// endpoint setting is needed that the client does not expose. The
277 /// idle-body watchdog (see [`Client::with_body_idle_timeout`]) is part of
278 /// the client rather than the endpoint and stays enabled.
279 ///
280 /// In particular, do not rely on
281 /// [`http2_adaptive_window`](tonic::transport::Endpoint::http2_adaptive_window)
282 /// as a substitute for large static windows: with adaptive windowing,
283 /// hyper starts the connection window at the 64 KiB HTTP/2 spec default
284 /// until bandwidth-delay probing ramps up, so a single stalled stream can
285 /// starve the whole connection.
286 pub fn from_endpoint(endpoint: &tonic::transport::Endpoint) -> Self {
287 let uri = endpoint.uri().clone();
288 let channel = build_channel(endpoint, DEFAULT_NUM_CONNECTIONS);
289 Self {
290 channel,
291 config: Arc::new(ClientConfig {
292 uri,
293 endpoint: endpoint.clone(),
294 headers: Default::default(),
295 max_decoding_message_size: None,
296 body_idle_timeout: Some(DEFAULT_BODY_IDLE_TIMEOUT),
297 num_connections: DEFAULT_NUM_CONNECTIONS,
298 request_layer: None,
299 }),
300 }
301 }
302
303 #[allow(clippy::result_large_err)]
304 pub fn new<T>(uri: T) -> Result<Self>
305 where
306 T: TryInto<http::Uri>,
307 T::Error: Into<BoxError>,
308 {
309 let uri = uri
310 .try_into()
311 .map_err(Into::into)
312 .map_err(status_from_error)?;
313 let mut endpoint = tonic::transport::Endpoint::from(uri.clone());
314 if uri.scheme() == Some(&http::uri::Scheme::HTTPS) {
315 endpoint = endpoint
316 .tls_config(ClientTlsConfig::new().with_enabled_roots())
317 .map_err(Into::into)
318 .map_err(status_from_error)?;
319 }
320
321 let endpoint = endpoint
322 .connect_timeout(DEFAULT_CONNECT_TIMEOUT)
323 .tcp_keepalive(Some(DEFAULT_TCP_KEEPALIVE_IDLE))
324 .tcp_keepalive_interval(Some(DEFAULT_TCP_KEEPALIVE_INTERVAL))
325 .tcp_keepalive_retries(Some(DEFAULT_TCP_KEEPALIVE_RETRIES))
326 .http2_keep_alive_interval(DEFAULT_HTTP2_KEEP_ALIVE_INTERVAL)
327 .keep_alive_timeout(DEFAULT_HTTP2_KEEP_ALIVE_TIMEOUT)
328 .initial_stream_window_size(DEFAULT_HTTP2_STREAM_WINDOW_SIZE)
329 .initial_connection_window_size(DEFAULT_HTTP2_CONNECTION_WINDOW_SIZE);
330 let channel = build_channel(&endpoint, DEFAULT_NUM_CONNECTIONS);
331
332 Ok(Self {
333 channel,
334 config: Arc::new(ClientConfig {
335 uri,
336 endpoint,
337 headers: Default::default(),
338 max_decoding_message_size: None,
339 body_idle_timeout: Some(DEFAULT_BODY_IDLE_TIMEOUT),
340 num_connections: DEFAULT_NUM_CONNECTIONS,
341 request_layer: None,
342 }),
343 })
344 }
345
346 /// Set the idle timeout for the client's response-body watchdog.
347 /// Defaults to 30 seconds.
348 ///
349 /// The watchdog bounds the time between response-body progress events: if
350 /// a whole idle period passes without a frame of the response being
351 /// delivered to the caller -- because the connection is starved or dead,
352 /// or because the caller has parked a streaming response without polling
353 /// it -- the watchdog resets the stream, releasing the HTTP/2
354 /// flow-control window it had pinned, and the call observes a
355 /// [`DeadlineExceeded`](tonic::Code::DeadlineExceeded) status on its next
356 /// poll. This is what turns "an RPC on a starved connection hangs
357 /// forever" into a bounded failure, and what keeps an abandoned stream
358 /// from starving the shared connection in the first place.
359 ///
360 /// Streams that are legitimately quiet for longer than the timeout (the
361 /// fullnode's checkpoint subscription is not: it emits watermarks every
362 /// few seconds) should raise or disable the watchdog for that call with a
363 /// [`BodyIdleTimeout`] request extension.
364 pub fn with_body_idle_timeout(mut self, timeout: Duration) -> Self {
365 Arc::make_mut(&mut self.config).body_idle_timeout = Some(timeout);
366 self
367 }
368
369 /// Disable the client's response-body watchdog (see
370 /// [`with_body_idle_timeout`](Self::with_body_idle_timeout)).
371 ///
372 /// Without it, an RPC whose response can no longer make progress hangs
373 /// indefinitely; only disable the watchdog when every call is bounded by
374 /// the caller. It can be re-enabled for individual requests with a
375 /// [`BodyIdleTimeout`] request extension.
376 pub fn without_body_idle_timeout(mut self) -> Self {
377 Arc::make_mut(&mut self.config).body_idle_timeout = None;
378 self
379 }
380
381 /// Set a timeout for the response-headers phase of every RPC made
382 /// through this client. Disabled by default.
383 ///
384 /// The timer covers a request from dispatch on the connection until
385 /// response headers arrive and is dropped once they do, so a client-wide
386 /// value does not cut off long-lived streaming responses. Because a
387 /// server does not send response headers for a unary call until the
388 /// handler completes, this effectively bounds the total duration of
389 /// unary calls; the body that follows is bounded by the idle-body
390 /// watchdog (see [`with_body_idle_timeout`](Self::with_body_idle_timeout))
391 /// and, when set, the per-call deadline. Connection establishment is
392 /// bounded separately by the connect timeout.
393 ///
394 /// This timeout is enforced locally only; it is not communicated to the
395 /// server. When a per-call deadline ([`tonic::Request::set_timeout`]) is
396 /// also set, the shorter of the two bounds the headers phase locally, so
397 /// a per-call deadline can tighten this bound but never extend it --
398 /// size the timeout for the slowest expected RPC. Expiry surfaces as
399 /// [`DeadlineExceeded`](tonic::Code::DeadlineExceeded).
400 ///
401 /// This rebuilds the underlying channel, so it must be called before the
402 /// client is used or cloned; earlier clones keep the previous
403 /// configuration.
404 pub fn with_response_headers_timeout(mut self, timeout: Duration) -> Self {
405 let config = Arc::make_mut(&mut self.config);
406 config.endpoint = config.endpoint.clone().timeout(timeout);
407 self.channel = build_channel(&config.endpoint, config.num_connections);
408 self
409 }
410
411 /// Set how many HTTP/2 connections the client opens to the endpoint.
412 /// Defaults to 1; a count of 0 is treated as 1.
413 ///
414 /// Requests are distributed across the connections rather than sharing
415 /// one connection's flow-control window and driver task. A single
416 /// connection's throughput is bounded by that window and by the one task
417 /// driving its multiplexed streams, so workloads that keep many streams
418 /// in flight at once (bulk or streaming reads) can be limited by it well
419 /// before the server is. Every connection carries the same endpoint
420 /// configuration, so the window sizes described in
421 /// [`with_initial_connection_window_size`](Self::with_initial_connection_window_size)
422 /// apply to each one, and the client's total window budget scales with
423 /// the count.
424 ///
425 /// Placement is effectively random per request, not a strict rotation, so
426 /// connections carry equal load only on average. Requests held open
427 /// concurrently, such as long-lived streams, can land unevenly.
428 ///
429 /// Connections are established lazily and reconnect independently, and
430 /// one that cannot be established fails only the requests routed to it.
431 ///
432 /// This rebuilds the underlying channel, so it must be called before the
433 /// client is used or cloned; earlier clones keep the previous
434 /// configuration.
435 pub fn with_num_connections(mut self, num_connections: usize) -> Self {
436 let config = Arc::make_mut(&mut self.config);
437 config.num_connections = num_connections.max(1);
438 self.channel = build_channel(&config.endpoint, config.num_connections);
439 self
440 }
441
442 /// Set the HTTP/2 per-stream receive window, in bytes.
443 ///
444 /// This bounds how much unread response data a single RPC can buffer
445 /// before the server must stop sending on that stream. It also bounds how
446 /// much of the shared connection window (see
447 /// [`with_initial_connection_window_size`](Self::with_initial_connection_window_size))
448 /// one stalled stream can pin. Defaults to 2 MiB.
449 ///
450 /// This rebuilds the underlying channel, so it must be called before the
451 /// client is used or cloned; earlier clones keep the previous
452 /// configuration.
453 pub fn with_initial_stream_window_size(mut self, size: u32) -> Self {
454 let config = Arc::make_mut(&mut self.config);
455 config.endpoint = config.endpoint.clone().initial_stream_window_size(size);
456 self.channel = build_channel(&config.endpoint, config.num_connections);
457 self
458 }
459
460 /// Set the HTTP/2 connection-level receive window, in bytes.
461 ///
462 /// This window is shared by every RPC multiplexed over one of the
463 /// client's HTTP/2 connections, including those issued by clones of the
464 /// client. Response data that the application has not yet read counts
465 /// against it, so it determines how many concurrently stalled streaming
466 /// responses it takes to starve a connection and hang every other RPC on
467 /// it. Defaults to 64 MiB (~32 stalled streams at the default 2 MiB
468 /// stream window). The window applies per connection, so a client
469 /// configured with
470 /// [`with_num_connections`](Self::with_num_connections) has this much on
471 /// each.
472 ///
473 /// This rebuilds the underlying channel, so it must be called before the
474 /// client is used or cloned; earlier clones keep the previous
475 /// configuration.
476 pub fn with_initial_connection_window_size(mut self, size: u32) -> Self {
477 let config = Arc::make_mut(&mut self.config);
478 config.endpoint = config.endpoint.clone().initial_connection_window_size(size);
479 self.channel = build_channel(&config.endpoint, config.num_connections);
480 self
481 }
482
483 pub fn with_headers(mut self, headers: HeadersInterceptor) -> Self {
484 Arc::make_mut(&mut self.config).headers = headers;
485 self
486 }
487
488 /// Provide an optional [`Layer`] that will be used to wrap all RPC
489 /// requests.
490 ///
491 /// This could be helpful in providing global metrics and logging
492 /// for all outbound requests.
493 ///
494 /// The layer's service may return any response body that implements
495 /// [`http_body::Body<Data = bytes::Bytes>`] and any error type that
496 /// implements `Into<Box<dyn Error + Send + Sync>>`. Both are mapped
497 /// to the internal types automatically.
498 ///
499 /// # Example
500 ///
501 /// Add a layer that logs each request URI:
502 ///
503 /// ```
504 /// # let _rt = tokio::runtime::Builder::new_current_thread()
505 /// # .build()
506 /// # .unwrap();
507 /// # let _guard = _rt.enter();
508 /// use sui_rpc::Client;
509 /// use tower::ServiceBuilder;
510 ///
511 /// let client = Client::new(Client::MAINNET_FULLNODE)
512 /// .unwrap()
513 /// .request_layer(ServiceBuilder::new().map_request(|req: http::Request<_>| {
514 /// println!("request to {}", req.uri());
515 /// req
516 /// }));
517 /// ```
518 pub fn request_layer<L, ResBody, E>(mut self, layer: L) -> Self
519 where
520 L: Layer<BoxService<http::Request<Body>, http::Response<Body>, BoxError>>
521 + Send
522 + Sync
523 + 'static,
524 L::Service: Service<http::Request<Body>, Response = http::Response<ResBody>, Error = E>
525 + Send
526 + 'static,
527 <L::Service as Service<http::Request<Body>>>::Future: Send + 'static,
528 ResBody: http_body::Body<Data = bytes::Bytes> + Send + 'static,
529 ResBody::Error: Into<BoxError>,
530 E: Into<BoxError> + Send + 'static,
531 {
532 let layer = BoxLayer::new(
533 ServiceBuilder::new()
534 .map_response(|resp: http::Response<ResBody>| resp.map(Body::new))
535 .map_err(Into::<BoxError>::into)
536 .layer(layer),
537 );
538 Arc::make_mut(&mut self.config).request_layer = Some(layer);
539 self
540 }
541
542 pub fn with_max_decoding_message_size(mut self, limit: usize) -> Self {
543 Arc::make_mut(&mut self.config).max_decoding_message_size = Some(limit);
544 self
545 }
546
547 pub fn uri(&self) -> &http::Uri {
548 &self.config.uri
549 }
550
551 fn channel(&self) -> BoxedChannel {
552 let headers = self.config.headers.clone();
553
554 // Build the base service with headers applied at the HTTP level and the
555 // transport error mapped to BoxError for compatibility with user layers.
556 let base = BoxService::new(
557 ServiceBuilder::new()
558 .map_request(move |mut req: http::Request<Body>| {
559 // Inserted before the configured headers so a caller can override it.
560 req.headers_mut().insert(
561 crate::headers::X_SUI_CLIENT_PROTOCOL_VERSION,
562 http::HeaderValue::from(crate::headers::MAX_PROTOCOL_VERSION),
563 );
564 if !headers.headers().is_empty() {
565 req.headers_mut()
566 .extend(headers.headers().clone().into_headers());
567 }
568 req
569 })
570 .service(UnsentRequestRetry::new(self.channel.clone())),
571 );
572
573 // Guard every response body with the idle-body watchdog, beneath any
574 // user layers so their view of the response goes through the
575 // watchdog's bridge.
576 let base = BoxService::new(WatchdogLayer::new(self.config.body_idle_timeout).layer(base));
577
578 // Apply the user's outbound request layer if present.
579 let layered = if let Some(layer) = &self.config.request_layer {
580 layer.layer(base)
581 } else {
582 base
583 };
584
585 // Map the final error to tonic::Status (a concrete type) so that
586 // downstream users of the tonic-generated clients don't run into
587 // lifetime-inference issues with async_trait and Box<dyn Error>.
588 BoxService::new(
589 ServiceBuilder::new()
590 .map_err(status_from_error)
591 .service(layered),
592 )
593 }
594
595 pub fn ledger_client(&mut self) -> LedgerServiceClient<BoxedChannel> {
596 LedgerServiceClient::new(self.channel())
597 .accept_compressed(CompressionEncoding::Zstd)
598 .pipe(|client| {
599 if let Some(limit) = self.config.max_decoding_message_size {
600 client.max_decoding_message_size(limit)
601 } else {
602 client
603 }
604 })
605 }
606
607 pub fn state_client(&mut self) -> StateServiceClient<BoxedChannel> {
608 StateServiceClient::new(self.channel())
609 .accept_compressed(CompressionEncoding::Zstd)
610 .pipe(|client| {
611 if let Some(limit) = self.config.max_decoding_message_size {
612 client.max_decoding_message_size(limit)
613 } else {
614 client
615 }
616 })
617 }
618
619 pub fn execution_client(&mut self) -> TransactionExecutionServiceClient<BoxedChannel> {
620 TransactionExecutionServiceClient::new(self.channel())
621 .accept_compressed(CompressionEncoding::Zstd)
622 .pipe(|client| {
623 if let Some(limit) = self.config.max_decoding_message_size {
624 client.max_decoding_message_size(limit)
625 } else {
626 client
627 }
628 })
629 }
630
631 pub fn package_client(&mut self) -> MovePackageServiceClient<BoxedChannel> {
632 MovePackageServiceClient::new(self.channel())
633 .accept_compressed(CompressionEncoding::Zstd)
634 .pipe(|client| {
635 if let Some(limit) = self.config.max_decoding_message_size {
636 client.max_decoding_message_size(limit)
637 } else {
638 client
639 }
640 })
641 }
642
643 pub fn signature_verification_client(
644 &mut self,
645 ) -> SignatureVerificationServiceClient<BoxedChannel> {
646 SignatureVerificationServiceClient::new(self.channel())
647 .accept_compressed(CompressionEncoding::Zstd)
648 .pipe(|client| {
649 if let Some(limit) = self.config.max_decoding_message_size {
650 client.max_decoding_message_size(limit)
651 } else {
652 client
653 }
654 })
655 }
656
657 pub fn subscription_client(&mut self) -> SubscriptionServiceClient<BoxedChannel> {
658 SubscriptionServiceClient::new(self.channel())
659 .accept_compressed(CompressionEncoding::Zstd)
660 .pipe(|client| {
661 if let Some(limit) = self.config.max_decoding_message_size {
662 client.max_decoding_message_size(limit)
663 } else {
664 client
665 }
666 })
667 }
668
669 /// Returns a client for the unstable alpha `ProofService`, which serves
670 /// Object Checkpoint State (OCS) inclusion proofs.
671 #[cfg(feature = "unstable")]
672 #[cfg_attr(doc_cfg, doc(cfg(feature = "unstable")))]
673 pub fn proof_client(&mut self) -> ProofServiceClient<BoxedChannel> {
674 ProofServiceClient::new(self.channel())
675 .accept_compressed(CompressionEncoding::Zstd)
676 .pipe(|client| {
677 if let Some(limit) = self.config.max_decoding_message_size {
678 client.max_decoding_message_size(limit)
679 } else {
680 client
681 }
682 })
683 }
684}
685
686/// Map a transport error to a [`tonic::Status`].
687///
688/// tonic surfaces an expired headers-phase timeout (the client's
689/// response-headers timeout, or a `grpc-timeout` deadline expiring before
690/// response headers arrive) as `Cancelled`. The gRPC code for an expired
691/// deadline is `DeadlineExceeded`, and the watchdog already uses it for
692/// body-phase expiry, so normalize before delegating to tonic's own mapping.
693fn status_from_error(error: BoxError) -> tonic::Status {
694 let mut source: Option<&(dyn std::error::Error + 'static)> = Some(error.as_ref());
695 while let Some(err) = source {
696 // An embedded `Status` takes precedence, as in tonic's own mapping.
697 if err.is::<tonic::Status>() {
698 break;
699 }
700 if err.is::<tonic::TimeoutExpired>() {
701 return tonic::Status::deadline_exceeded(
702 "timeout expired before response headers were received",
703 );
704 }
705 source = err.source();
706 }
707 tonic::Status::from_error(error)
708}