Skip to main content

sui_rpc/client/ledger_streams/adapter/
checkpoint.rs

1use prost::bytes::Bytes;
2use tonic::Request;
3use tonic::Status;
4use tonic::codegen::BoxStream;
5
6use super::super::super::Client;
7use super::super::super::Result;
8use super::super::observability::LedgerStreamFamily;
9use super::super::types::CheckpointStreamFrame;
10use super::BoundFields;
11use super::KeyGranularity;
12use super::LedgerFrame;
13use super::ListScanDirection;
14use super::Position;
15use super::Progress;
16use super::RpcFuture;
17use super::SubscriptionAdapter;
18use crate::proto::sui::rpc::v2::Checkpoint;
19use crate::proto::sui::rpc::v2::ListCheckpointsRequest;
20use crate::proto::sui::rpc::v2::ListCheckpointsResponse;
21use crate::proto::sui::rpc::v2::QueryEnd;
22use crate::proto::sui::rpc::v2::QueryOptions;
23use crate::proto::sui::rpc::v2::SubscribeCheckpointsRequest;
24use crate::proto::sui::rpc::v2::SubscribeCheckpointsResponse;
25use crate::proto::sui::rpc::v2::Watermark;
26
27pub(in crate::client::ledger_streams) struct CheckpointAdapter;
28
29impl SubscriptionAdapter for CheckpointAdapter {
30    const FAMILY: LedgerStreamFamily = LedgerStreamFamily::Checkpoint;
31    const GRANULARITY: KeyGranularity = KeyGranularity::Checkpoint;
32
33    type Item = Checkpoint;
34    /// Checkpoint positions are dense, so `start_checkpoint` and `end_checkpoint` bound requests
35    /// without opaque cursors.
36    type Cursor = ();
37    type Output = CheckpointStreamFrame;
38    type ListRequest = ListCheckpointsRequest;
39    type ListResponse = ListCheckpointsResponse;
40    type SubscribeRequest = SubscribeCheckpointsRequest;
41    type SubscribeResponse = SubscribeCheckpointsResponse;
42
43    fn options(request: &Self::ListRequest) -> Option<&QueryOptions> {
44        request.options.as_ref()
45    }
46
47    fn options_mut(request: &mut Self::ListRequest) -> &mut QueryOptions {
48        request.options.get_or_insert_with(QueryOptions::default)
49    }
50
51    fn start_checkpoint(request: &Self::ListRequest) -> Option<u64> {
52        request.start_checkpoint
53    }
54
55    fn end_checkpoint(request: &Self::ListRequest) -> Option<u64> {
56        request.end_checkpoint
57    }
58
59    fn set_start_fields(request: &mut Self::ListRequest, fields: BoundFields) {
60        request.start_checkpoint = Some(fields.checkpoint);
61    }
62
63    fn set_end_fields(request: &mut Self::ListRequest, fields: BoundFields) {
64        request.end_checkpoint = Some(fields.checkpoint);
65    }
66
67    /// A checkpoint scan that ends at its checkpoint bound has covered the checkpoint at that
68    /// bound: `end_checkpoint - 1` ascending, `start_checkpoint` descending.
69    fn validate_checkpoint_bound(
70        request: &Self::ListRequest,
71        direction: ListScanDirection,
72        checkpoint: Option<u64>,
73    ) -> Result<()> {
74        let expected_checkpoint = match direction {
75            ListScanDirection::Ascending => {
76                request.end_checkpoint.and_then(|end| end.checked_sub(1))
77            }
78            ListScanDirection::Descending => Some(request.start_checkpoint.unwrap_or(0)),
79        };
80        if checkpoint.is_some() && checkpoint != expected_checkpoint {
81            Err(Status::data_loss(
82                "List CheckpointBound watermark does not match the requested bound",
83            ))
84        } else {
85            Ok(())
86        }
87    }
88
89    fn cursor_bytes(_cursor: &Self::Cursor) -> Option<Bytes> {
90        None
91    }
92
93    fn list_cursor(_cursor: Bytes) -> Self::Cursor {}
94
95    fn extract_metadata(
96        response: &Self::ListResponse,
97    ) -> (bool, Option<&Watermark>, Option<&QueryEnd>) {
98        (
99            response.checkpoint.is_some(),
100            response.watermark.as_ref(),
101            response.end.as_ref(),
102        )
103    }
104
105    fn into_list_item(response: Self::ListResponse) -> Option<Self::Item> {
106        response.checkpoint
107    }
108
109    fn item_required(request: &Self::SubscribeRequest) -> bool {
110        request.filter.is_none()
111    }
112
113    fn parse_live(
114        response: Self::SubscribeResponse,
115        item_required: bool,
116    ) -> Result<LedgerFrame<Self::Item, Self::Cursor>> {
117        let cursor = response.cursor.ok_or_else(|| {
118            Status::data_loss("checkpoint subscription frame is missing its cursor")
119        })?;
120        if response.checkpoint.is_none() && item_required {
121            return Err(Status::data_loss(
122                "unfiltered checkpoint subscription frame is missing its checkpoint",
123            ));
124        }
125        // `cursor` is the inclusive checkpoint covered, so the frame's position is the start of
126        // the next checkpoint.
127        let next_checkpoint = cursor.checked_add(1).ok_or_else(|| {
128            Status::out_of_range("checkpoint subscription cursor cannot be resumed")
129        })?;
130        LedgerFrame::new(
131            response.checkpoint,
132            Progress {
133                position: Position::checkpoint_start(next_checkpoint),
134                cursor: (),
135                checkpoint: Some(cursor),
136            },
137            Self::GRANULARITY,
138        )
139    }
140
141    fn into_output(item: Option<Self::Item>, progress: Progress<Self::Cursor>) -> Self::Output {
142        CheckpointStreamFrame {
143            checkpoint: item,
144            // Output frames lie past the start of the stream, so their position is at least 1.
145            cursor: progress.position.checkpoint.saturating_sub(1),
146        }
147    }
148
149    fn dispatch_list(
150        mut client: Client,
151        request: Request<Self::ListRequest>,
152    ) -> RpcFuture<Self::ListResponse> {
153        Box::pin(async move {
154            let stream = client
155                .ledger_client()
156                .list_checkpoints(request)
157                .await?
158                .into_inner();
159            Ok(Box::pin(stream) as BoxStream<Self::ListResponse>)
160        })
161    }
162
163    fn dispatch_subscribe(
164        mut client: Client,
165        request: Request<Self::SubscribeRequest>,
166    ) -> RpcFuture<Self::SubscribeResponse> {
167        Box::pin(async move {
168            let stream = client
169                .subscription_client()
170                .subscribe_checkpoints(request)
171                .await?
172                .into_inner();
173            Ok(Box::pin(stream) as BoxStream<Self::SubscribeResponse>)
174        })
175    }
176}