Skip to content
Draft
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
81 changes: 57 additions & 24 deletions crates/sui-rpc/src/client/ledger_streams/retry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ pub(super) enum RequestBounds {

/// Classifies failures eligible for automatic retry.
///
/// `Unavailable`, `DeadlineExceeded`, `ResourceExhausted`, and `Aborted` are always retried.
/// `Unavailable`, `DeadlineExceeded`, `ResourceExhausted`, and `Aborted` are retried, except a
/// `ResourceExhausted` with the [`ErrorReason::ResponseTooLarge`] reason: an item's size does not
/// change, so the same request fails the same way on every attempt.
///
/// `Cancelled` and `Unknown` use two heuristics based on where the error was observed:
/// - During `Dispatch` (initiating the RPC), server-sent `Cancelled` and `Unknown` are
Expand All @@ -66,12 +68,20 @@ fn transient(status: &Status, phase: FailurePhase, bounds: RequestBounds) -> boo
let dispatch_transient = matches!(
status.code(),
Code::Unavailable | Code::DeadlineExceeded | Code::ResourceExhausted | Code::Aborted
);
) && !response_too_large(status);
let reset_code = matches!(status.code(), Code::Cancelled | Code::Unknown);
let transport_reset = reset_code && (phase == FailurePhase::Body || status.source().is_some());
dispatch_transient || transport_reset || above_latest_available_is_transient(status, bounds)
}

/// Whether `status` is a `ResourceExhausted` whose status details carry an `ErrorInfo` with reason
/// [`ErrorReason::ResponseTooLarge`].
fn response_too_large(status: &Status) -> bool {
status.code() == Code::ResourceExhausted
&& sui_error_infos(status)
.any(|error_info| error_info.reason == ErrorReason::ResponseTooLarge.as_str_name())
}

/// Whether `status` is an `OutOfRange` whose status details carry an `ErrorInfo` with reason
/// [`ErrorReason::AboveLatestAvailable`] for a bound some server reported: any bound of a request
/// whose bounds are [`RequestBounds::ServerReported`], or the `bound` metadata `"cursor"`, since
Expand All @@ -81,22 +91,23 @@ fn above_latest_available_is_transient(status: &Status, bounds: RequestBounds) -
if status.code() != Code::OutOfRange {
return false;
}
let Ok(details) = crate::proto::google::rpc::Status::decode(status.details()) else {
return false;
};
details
.details
.iter()
sui_error_infos(status).any(|error_info| {
error_info.reason == ErrorReason::AboveLatestAvailable.as_str_name()
&& (bounds == RequestBounds::ServerReported
|| error_info
.metadata
.get("bound")
.is_some_and(|bound| bound == "cursor"))
})
}

/// The `ErrorInfo`s in `status`'s details whose domain is [`ErrorReason::DOMAIN`].
fn sui_error_infos(status: &Status) -> impl Iterator<Item = ErrorInfo> {
crate::proto::google::rpc::Status::decode(status.details())
.into_iter()
.flat_map(|details| details.details)
.filter_map(|detail| detail.to_msg::<ErrorInfo>().ok())
.any(|error_info| {
error_info.domain == ErrorReason::DOMAIN
&& error_info.reason == ErrorReason::AboveLatestAvailable.as_str_name()
&& (bounds == RequestBounds::ServerReported
|| error_info
.metadata
.get("bound")
.is_some_and(|bound| bound == "cursor"))
})
.filter(|error_info| error_info.domain == ErrorReason::DOMAIN)
}

pub(super) struct RetryState {
Expand Down Expand Up @@ -245,7 +256,7 @@ mod tests {
assert!(transient(&status, FailurePhase::Body, CALLER));
}

fn out_of_range_with_reason(reason: ErrorReason, bound: Option<&str>) -> Status {
fn status_with_reason(code: Code, reason: ErrorReason, bound: Option<&str>) -> Status {
let mut error_info = ErrorInfo::default()
.with_domain(ErrorReason::DOMAIN)
.with_reason(reason.as_str_name());
Expand All @@ -255,19 +266,40 @@ mod tests {
.insert("bound".to_owned(), bound.to_owned());
}
let details = crate::proto::google::rpc::Status {
code: Code::OutOfRange.into(),
message: "requested data out of range".to_owned(),
code: code.into(),
message: "request failed".to_owned(),
details: vec![prost_types::Any::from_msg(&error_info).unwrap()],
};
Status::with_details(
Code::OutOfRange,
code,
details.message.clone(),
details.encode_to_vec().into(),
)
}

fn above_latest_available(bound: &str) -> Status {
out_of_range_with_reason(ErrorReason::AboveLatestAvailable, Some(bound))
status_with_reason(
Code::OutOfRange,
ErrorReason::AboveLatestAvailable,
Some(bound),
)
}

#[test]
fn response_too_large_is_terminal_in_both_phases() {
let status =
status_with_reason(Code::ResourceExhausted, ErrorReason::ResponseTooLarge, None);
for bounds in [CALLER, SERVER] {
assert!(!transient(&status, FailurePhase::Dispatch, bounds));
assert!(!transient(&status, FailurePhase::Body, bounds));
}
}

#[test]
fn resource_exhausted_without_response_too_large_is_transient() {
let status = Status::resource_exhausted("rate limited");
assert!(transient(&status, FailurePhase::Dispatch, CALLER));
assert!(transient(&status, FailurePhase::Body, CALLER));
}

#[test]
Expand Down Expand Up @@ -306,8 +338,9 @@ mod tests {
#[test]
fn out_of_range_without_a_server_reported_bound_past_the_tip_is_terminal() {
let below_earliest_available =
out_of_range_with_reason(ErrorReason::BelowEarliestAvailable, None);
let missing_bound = out_of_range_with_reason(ErrorReason::AboveLatestAvailable, None);
status_with_reason(Code::OutOfRange, ErrorReason::BelowEarliestAvailable, None);
let missing_bound =
status_with_reason(Code::OutOfRange, ErrorReason::AboveLatestAvailable, None);
let without_reason = Status::out_of_range("requested data above latest available");
for status in [
below_earliest_available.clone(),
Expand Down
37 changes: 37 additions & 0 deletions crates/sui-rpc/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ use crate::proto::sui::rpc::v2::subscription_service_client::SubscriptionService
use crate::proto::sui::rpc::v2::transaction_execution_service_client::TransactionExecutionServiceClient;
#[cfg(feature = "unstable")]
use crate::proto::sui::rpc::v2alpha::proof_service_client::ProofServiceClient;
#[cfg(feature = "unstable")]
use crate::proto::sui::rpc::v2beta::ledger_service_client::LedgerServiceClient as BetaLedgerServiceClient;
#[cfg(feature = "unstable")]
use crate::proto::sui::rpc::v2beta::subscription_service_client::SubscriptionServiceClient as BetaSubscriptionServiceClient;

type Result<T, E = tonic::Status> = std::result::Result<T, E>;
type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
Expand Down Expand Up @@ -681,6 +685,39 @@ impl Client {
}
})
}

/// Returns a client for the unstable beta `LedgerService`
/// (`sui.rpc.v2beta`), which reads checkpoints as streams of bounded-size
/// parts.
#[cfg(feature = "unstable")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "unstable")))]
pub fn beta_ledger_client(&mut self) -> BetaLedgerServiceClient<BoxedChannel> {
BetaLedgerServiceClient::new(self.channel())
.accept_compressed(CompressionEncoding::Zstd)
.pipe(|client| {
if let Some(limit) = self.config.max_decoding_message_size {
client.max_decoding_message_size(limit)
} else {
client
}
})
}

/// Returns a client for the unstable beta `SubscriptionService`
/// (`sui.rpc.v2beta`), which streams new checkpoints as bounded-size parts.
#[cfg(feature = "unstable")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "unstable")))]
pub fn beta_subscription_client(&mut self) -> BetaSubscriptionServiceClient<BoxedChannel> {
BetaSubscriptionServiceClient::new(self.channel())
.accept_compressed(CompressionEncoding::Zstd)
.pipe(|client| {
if let Some(limit) = self.config.max_decoding_message_size {
client.max_decoding_message_size(limit)
} else {
client
}
})
}
}

/// Map a transport error to a [`tonic::Status`].
Expand Down
Binary file modified crates/sui-rpc/src/proto/generated/sui.rpc.v2.fds.bin
Binary file not shown.
64 changes: 64 additions & 0 deletions crates/sui-rpc/src/proto/generated/sui.rpc.v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1196,6 +1196,54 @@ pub enum ErrorReason {
///
/// It carries no metadata.
VersionNotRetained = 10,
/// A single response message, rendered for the request's `read_mask`, would
/// be larger than the largest response message this server sends. Returned
/// with `RESOURCE_EXHAUSTED` by RPCs that send each item in one message: the
/// checkpoint RPCs `GetCheckpoint`, `ListCheckpoints` and
/// `SubscribeCheckpoints`, and the transaction and batch RPCs such as
/// `GetTransaction`, `BatchGetTransactions`, `ListTransactions` and
/// `SubscribeTransactions`.
///
/// A `List*` stream first delivers the items before the one that is too
/// large, then a frame without an item whose watermark resumes at it, and
/// then fails with this error. A `Subscribe*` stream ends with this error
/// rather than skip the item.
///
/// An item's size does not change, so requesting the same item with the
/// same `read_mask` fails the same way on this server. To read it:
///
/// * Narrow `read_mask`: for example, request a checkpoint's
/// `summary,signature` only, or leave out `objects` or `events` and fetch
/// them separately with `BatchGetObjects` or `ListEvents`.
/// * For a `BatchGet*` request, ask for fewer items per request.
/// * For a checkpoint, read it in bounded-size parts with
/// `sui.rpc.v2beta.LedgerService` `GetCheckpointParts` or
/// `ListCheckpointParts`, or `sui.rpc.v2beta.SubscriptionService`
/// `SubscribeCheckpointParts`.
///
/// Example of an ErrorInfo for checkpoint 1205 from a server whose message
/// limit is 128 MiB:
///
/// ```text
/// { "reason": "RESPONSE_TOO_LARGE",
/// "domain": "sui.io",
/// "metadata": {
/// "checkpoint": "1205",
/// "maxMessageBytes": "134217728"
/// }
/// }
/// ```
///
/// Metadata:
///
/// * `maxMessageBytes`: the server's limit on the size of a single response
/// message, in bytes, as a decimal string. Always present.
/// * `checkpoint`: the sequence number of the checkpoint that is too large,
/// or that contains the transaction that is too large, as a decimal
/// string. Set by the checkpoint RPCs; transaction RPCs may set it.
/// * `transaction`: the digest of the transaction that is too large, in
/// Base58. Set when a single transaction exceeds the limit.
ResponseTooLarge = 11,
}
impl ErrorReason {
/// String value of the enum field names used in the ProtoBuf definition.
Expand All @@ -1215,6 +1263,7 @@ impl ErrorReason {
Self::NotServedHere => "NOT_SERVED_HERE",
Self::NotReady => "NOT_READY",
Self::VersionNotRetained => "VERSION_NOT_RETAINED",
Self::ResponseTooLarge => "RESPONSE_TOO_LARGE",
}
}
/// Creates an enum from field names used in the ProtoBuf definition.
Expand All @@ -1231,6 +1280,7 @@ impl ErrorReason {
"NOT_SERVED_HERE" => Some(Self::NotServedHere),
"NOT_READY" => Some(Self::NotReady),
"VERSION_NOT_RETAINED" => Some(Self::VersionNotRetained),
"RESPONSE_TOO_LARGE" => Some(Self::ResponseTooLarge),
_ => None,
}
}
Expand Down Expand Up @@ -3162,6 +3212,10 @@ pub mod get_transaction_result {
/// `BELOW_EARLIEST_AVAILABLE`: by `sequence_number` always, by `digest` while
/// it can still find the checkpoint. A digest it can no longer find is
/// `NOT_FOUND`.
///
/// A checkpoint too large to send in one message for the requested
/// `read_mask` fails with `RESOURCE_EXHAUSTED` and reason
/// `RESPONSE_TOO_LARGE`.
#[non_exhaustive]
#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
pub struct GetCheckpointRequest {
Expand Down Expand Up @@ -3236,6 +3290,12 @@ pub struct GetProtocolConfigResponse {
pub protocol_config: ::core::option::Option<ProtocolConfig>,
}
/// Request message for LedgerService.ListCheckpoints.
///
/// A checkpoint too large to send in one message for the requested
/// `read_mask` ends the stream with `RESOURCE_EXHAUSTED` and reason
/// `RESPONSE_TOO_LARGE`. Before the error, the stream delivers the
/// checkpoints before it and then a frame without a checkpoint whose
/// watermark resumes at it.
#[non_exhaustive]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ListCheckpointsRequest {
Expand Down Expand Up @@ -9474,6 +9534,10 @@ pub mod state_service_server {
}
}
/// Request message for SubscriptionService.SubscribeCheckpoints.
///
/// A checkpoint too large to send in one message for the requested
/// `read_mask` ends the stream with `RESOURCE_EXHAUSTED` and reason
/// `RESPONSE_TOO_LARGE`.
#[derive(Eq, Hash)]
#[non_exhaustive]
#[derive(Clone, PartialEq, ::prost::Message)]
Expand Down
3 changes: 3 additions & 0 deletions crates/sui-rpc/src/proto/generated/sui.rpc.v2.serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10317,6 +10317,7 @@ impl serde::Serialize for ErrorReason {
Self::NotServedHere => "NOT_SERVED_HERE",
Self::NotReady => "NOT_READY",
Self::VersionNotRetained => "VERSION_NOT_RETAINED",
Self::ResponseTooLarge => "RESPONSE_TOO_LARGE",
};
serializer.serialize_str(variant)
}
Expand All @@ -10339,6 +10340,7 @@ impl<'de> serde::Deserialize<'de> for ErrorReason {
"NOT_SERVED_HERE",
"NOT_READY",
"VERSION_NOT_RETAINED",
"RESPONSE_TOO_LARGE",
];
struct GeneratedVisitor;
impl<'de> serde::de::Visitor<'de> for GeneratedVisitor {
Expand Down Expand Up @@ -10395,6 +10397,7 @@ impl<'de> serde::Deserialize<'de> for ErrorReason {
"NOT_SERVED_HERE" => Ok(ErrorReason::NotServedHere),
"NOT_READY" => Ok(ErrorReason::NotReady),
"VERSION_NOT_RETAINED" => Ok(ErrorReason::VersionNotRetained),
"RESPONSE_TOO_LARGE" => Ok(ErrorReason::ResponseTooLarge),
_ => Err(serde::de::Error::unknown_variant(value, FIELDS)),
}
}
Expand Down
Loading
Loading