Skip to main content

sui_rpc_api/ledger_history/
watermark.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Shared `Watermark` construction for the v2 list APIs.
5//!
6//! Both ledger-history backends — the fullnode (`sui-rpc-api`) and bigtable
7//! (`sui-kv-rpc`) — and all three list handlers (`list_transactions`,
8//! `list_events`, `list_checkpoints`) emit the same wire `Watermark`: a resume
9//! cursor, the same resume point in ledger coordinates (`cursor_position`, a
10//! [`LedgerPoint`]), and a completion boundary
11//! (`checkpoint`, the inclusive boundary checkpoint the scan has fully covered
12//! in the request's ordering direction).
13//! The cursor encoding and the boundary bookkeeping are identical; what differs
14//! per API is how a scan position resolves into a completion-boundary candidate:
15//!
16//! - `list_transactions` / `list_events` scan within a checkpoint, so an
17//!   item at checkpoint `C` does NOT prove `C` complete (more matches may sit
18//!   at higher/lower transaction or event positions). Their covered bound is
19//!   advanced before `C` — see [`advance_covered_bound_before_checkpoint`].
20//! - `list_checkpoints` dedupes checkpoint numbers, so "checkpoint `C`
21//!   emitted" means "checkpoint `C` complete." Its item path directly records
22//!   `C`; independently resolved frontier candidates are folded with
23//!   [`merge_covered_checkpoint_bound`].
24//!
25//! This module owns the shared pieces; each handler keeps only its
26//! API-specific frontier-to-candidate adapter.
27
28use sui_inverted_index::ScanDirection;
29use sui_rpc::proto::sui::rpc::v2::QueryEndReason;
30use sui_rpc::proto::sui::rpc::v2::Watermark;
31
32use crate::RpcError;
33use crate::ledger_history::cursor::{CursorKind, CursorToken, LedgerPoint, Position};
34use crate::ledger_history::query_options::{QueryOptions, RangeExhaustion, below_serving_floor};
35
36/// Populate the completion-boundary `checkpoint` field of a `Watermark` from
37/// the per-scan boundary value. The value already carries the direction-correct
38/// meaning (inclusive upper bound ascending, inclusive lower bound descending);
39/// the single wire field records it regardless of ordering.
40fn set_checkpoint_bound(wm: &mut Watermark, boundary: Option<u64>) {
41    wm.checkpoint = boundary;
42}
43
44/// Merge a fully covered checkpoint candidate into the accumulated inclusive
45/// bound. The bound advances by max in ascending scans and min in descending
46/// scans.
47pub fn merge_covered_checkpoint_bound(
48    covered_checkpoint_bound: Option<u64>,
49    candidate_bound: u64,
50    options: &QueryOptions,
51) -> Option<u64> {
52    Some(match covered_checkpoint_bound {
53        None => candidate_bound,
54        Some(bound) if options.is_ascending() => bound.max(candidate_bound),
55        Some(bound) => bound.min(candidate_bound),
56    })
57}
58
59/// Advance the inclusive covered bound using a checkpoint that is not itself
60/// proven complete. Transactions, events, and scan frontiers can leave more
61/// matches within checkpoint `C`, so the candidate excludes `C`: `C - 1`
62/// ascending and `C + 1` descending. The adjusted candidate is then merged by
63/// max ascending or min descending.
64///
65/// `entry_checkpoint` is the window's first checkpoint in scan direction
66/// (raised to the serving floor ascending). A candidate strictly before it
67/// lies outside the window, and is discarded. Within the window, a candidate
68/// counts even before the scan reads its checkpoint's start: the request's
69/// starting cursor vouches for every position before it.
70///
71/// When the `C ∓ 1` adjustment would overflow (`C == 0` ascending or
72/// `u64::MAX` descending), the previously covered bound is preserved.
73pub fn advance_covered_bound_before_checkpoint(
74    covered_checkpoint_bound: Option<u64>,
75    incomplete_checkpoint: u64,
76    entry_checkpoint: u64,
77    options: &QueryOptions,
78) -> Option<u64> {
79    let candidate_bound = if options.is_ascending() {
80        incomplete_checkpoint
81            .checked_sub(1)
82            .filter(|candidate| *candidate >= entry_checkpoint)
83    } else {
84        incomplete_checkpoint
85            .checked_add(1)
86            .filter(|candidate| *candidate <= entry_checkpoint)
87    };
88    match candidate_bound {
89        Some(candidate_bound) => {
90            merge_covered_checkpoint_bound(covered_checkpoint_bound, candidate_bound, options)
91        }
92        None => covered_checkpoint_bound,
93    }
94}
95
96/// Build the embedded `Watermark` for an item: the cursor encodes this
97/// item's position (so the next request's `after`/`before` resumes past it)
98/// plus the current direction-matching checkpoint boundary. `position` is the
99/// item's cursor coordinates (`list_checkpoints` passes its cp_seq), whose
100/// public position is the item's key in ledger coordinates; the frame's
101/// `cursor_position` follows from it (see [`Position::item_resume`]).
102pub fn item_watermark(
103    position: Position,
104    direction: ScanDirection,
105    boundary: Option<u64>,
106) -> Watermark {
107    cursor_watermark(
108        position,
109        CursorKind::Item,
110        position.item_resume(direction),
111        boundary,
112    )
113}
114
115/// Build a standalone scan-frontier `Watermark`. `position` is the boundary
116/// cursor coordinates the caller has already resolved for its scan domain (see
117/// [`boundary_cursor_cp`] for the checkpoint scanners' direction adjustment),
118/// whose public position is where the frame resumes; `boundary` the
119/// accumulated completion boundary.
120pub fn boundary_watermark(position: Position, boundary: Option<u64>) -> Watermark {
121    cursor_watermark(
122        position,
123        CursorKind::Boundary,
124        position.public_position(),
125        boundary,
126    )
127}
128
129/// Build a watermark with a `cursor_kind` cursor at `position`, the one place
130/// every frame's cursor is minted. The frame resumes at `cursor_position`. A
131/// terminal's kind comes from query-range bookkeeping (see
132/// [`RangeExhaustion::CursorBound`]): an `after` Item cursor at the last
133/// position names no boundary after it, so its closing cursor keeps Item kind
134/// where a Boundary at its position would re-include the item on resume.
135fn cursor_watermark(
136    position: Position,
137    cursor_kind: CursorKind,
138    cursor_position: LedgerPoint,
139    boundary: Option<u64>,
140) -> Watermark {
141    let cursor = CursorToken {
142        kind: cursor_kind,
143        position,
144    };
145    let mut wm = Watermark::default();
146    wm.cursor = Some(cursor.encode());
147    wm.cursor_position = Some(cursor_position.to_ledger_position(&position));
148    set_checkpoint_bound(&mut wm, boundary);
149    wm
150}
151
152/// Resolve the checkpoint coordinate of a `list_checkpoints` boundary cursor
153/// at a scan frontier inside checkpoint `cp`. The cursor encoding is
154/// asymmetric: ascending `Boundary` cursors resume at their checkpoint, so the
155/// frontier cp is used directly; descending `Boundary` cursors treat the
156/// checkpoint as an EXCLUSIVE upper bound, so `cp + 1` is needed to keep `cp`
157/// itself included on resume.
158pub fn boundary_cursor_cp(cp: u64, direction: ScanDirection) -> u64 {
159    if direction.is_ascending() {
160        cp
161    } else {
162        cp.saturating_add(1)
163    }
164}
165
166/// Terminal of a successful list scan that renders as the trailing
167/// payload-free `QueryEnd` frame. `ItemLimit` never reaches this type: the
168/// drive loops fuse it onto the final item frame and suppress the trailing
169/// frame. The wire reason and the watermark policy are projections of the
170/// same value, so they cannot disagree.
171#[derive(Clone, Copy, Debug, Eq, PartialEq)]
172pub enum NaturalRangeEnd {
173    LedgerTip,
174    CheckpointBound,
175}
176
177/// Where a list scan ends once it drains its resolved range, as its terminal frame renders it
178/// (see [`ResolvedScan::range_end`]).
179///
180/// [`ResolvedScan::range_end`]: crate::ledger_history::query_options::ResolvedScan::range_end
181#[derive(Clone, Copy, Debug, Eq, PartialEq)]
182pub struct RangeEnd {
183    /// Why the range is exhausted.
184    pub exhaustion: RangeExhaustion,
185    /// The terminal cursor's coordinates and public position (see
186    /// [`ResolvedScan::end_cursor_public_position`]).
187    ///
188    /// [`ResolvedScan::end_cursor_public_position`]: crate::ledger_history::query_options::ResolvedScan::end_cursor_public_position
189    pub position: Position,
190    /// Where the terminal frame resumes in ledger coordinates (see
191    /// [`ResolvedScan::end_resume_position`]).
192    ///
193    /// [`ResolvedScan::end_resume_position`]: crate::ledger_history::query_options::ResolvedScan::end_resume_position
194    pub cursor_position: LedgerPoint,
195    /// The checkpoint a natural end claims (see [`ResolvedScan::natural_end_claim`]).
196    ///
197    /// [`ResolvedScan::natural_end_claim`]: crate::ledger_history::query_options::ResolvedScan::natural_end_claim
198    pub natural_end_claim: Option<u64>,
199}
200
201impl RangeEnd {
202    /// The terminal a scan reaches at this end.
203    pub fn terminal(self) -> ScanTerminal {
204        ScanTerminal::from_range_exhaustion(
205            self.exhaustion,
206            self.position,
207            self.cursor_position,
208            self.natural_end_claim,
209        )
210    }
211}
212
213#[derive(Clone, Debug, PartialEq)]
214pub enum ScanTerminal {
215    /// Scan budget exhausted. Owns the mandatory authoritative frontier
216    /// watermark (its cursor is always set by the frontier constructors).
217    ScanLimit { watermark: Watermark },
218    /// The resolved interval is naturally exhausted at `position`.
219    NaturalRange {
220        end: NaturalRangeEnd,
221        position: Position,
222        /// Where the frame resumes (see [`ResolvedScan::end_resume_position`]).
223        ///
224        /// [`ResolvedScan::end_resume_position`]: crate::ledger_history::query_options::ResolvedScan::end_resume_position
225        cursor_position: LedgerPoint,
226        /// The checkpoint this page's natural end reports as fully covered in
227        /// `Watermark.checkpoint`, or `None` when nothing remains to claim: the window has no
228        /// checkpoint, or an ascending scan ends at genesis. See
229        /// [`ResolvedScan::natural_end_claim`].
230        ///
231        /// [`ResolvedScan::natural_end_claim`]: crate::ledger_history::query_options::ResolvedScan::natural_end_claim
232        claimed_checkpoint: Option<u64>,
233    },
234    /// The caller-provided cursor bound truncates the interval at `position`.
235    CursorBound {
236        position: Position,
237        cursor_position: LedgerPoint,
238        kind: CursorKind,
239    },
240    /// A descending scan with no lower bound of its own reached this server's serving floor at
241    /// `position`; everything below is pruned. It never renders as a `QueryEnd`: below the item
242    /// limit, the stream sends a payload-free frame with [`Self::into_watermark`] and no `end`,
243    /// then fails with the error [`Self::reason`] returns for it.
244    ServingFloor {
245        position: Position,
246        cursor_position: LedgerPoint,
247        floor_checkpoint: u64,
248    },
249}
250
251impl ScanTerminal {
252    /// The terminal a scan reaches once it exhausts its resolved interval at `position`, resuming
253    /// at `cursor_position` in ledger coordinates.
254    pub fn from_range_exhaustion(
255        exhaustion: RangeExhaustion,
256        position: Position,
257        cursor_position: LedgerPoint,
258        claimed_checkpoint: Option<u64>,
259    ) -> Self {
260        match exhaustion {
261            RangeExhaustion::LedgerTip => Self::NaturalRange {
262                end: NaturalRangeEnd::LedgerTip,
263                position,
264                cursor_position,
265                claimed_checkpoint,
266            },
267            RangeExhaustion::CheckpointBound => Self::NaturalRange {
268                end: NaturalRangeEnd::CheckpointBound,
269                position,
270                cursor_position,
271                claimed_checkpoint,
272            },
273            RangeExhaustion::CursorBound { kind } => Self::CursorBound {
274                position,
275                cursor_position,
276                kind,
277            },
278            RangeExhaustion::ServingFloor { floor_checkpoint } => Self::ServingFloor {
279                position,
280                cursor_position,
281                floor_checkpoint,
282            },
283        }
284    }
285
286    /// The `QueryEnd` reason this terminal ends its page with. [`Self::ServingFloor`] ends its page
287    /// with no `QueryEnd`, so for it this is the `OutOfRange` error its stream fails with instead,
288    /// after the terminal watermark frame.
289    pub fn reason(&self) -> Result<QueryEndReason, RpcError> {
290        match self {
291            Self::ScanLimit { .. } => Ok(QueryEndReason::ScanLimit),
292            Self::NaturalRange {
293                end: NaturalRangeEnd::LedgerTip,
294                ..
295            } => Ok(QueryEndReason::LedgerTip),
296            Self::NaturalRange {
297                end: NaturalRangeEnd::CheckpointBound,
298                ..
299            } => Ok(QueryEndReason::CheckpointBound),
300            Self::CursorBound { .. } => Ok(QueryEndReason::CursorBound),
301            Self::ServingFloor {
302                floor_checkpoint, ..
303            } => Err(below_serving_floor(*floor_checkpoint)),
304        }
305    }
306
307    /// Render the trailing terminal frame's watermark. Natural completion
308    /// (LedgerTip/CheckpointBound) claims its `claimed_checkpoint` and ignores
309    /// `covered_checkpoint_bound` (the range claim is always at least as
310    /// strong). A cursor bound never claims its own checkpoint: its claim is
311    /// exactly the accumulated item coverage. A serving floor claims the floor
312    /// checkpoint behind a boundary cursor at the floor.
313    pub fn into_watermark(self, covered_checkpoint_bound: Option<u64>) -> Watermark {
314        match self {
315            Self::ScanLimit { watermark } => watermark,
316            Self::NaturalRange {
317                position,
318                cursor_position,
319                claimed_checkpoint,
320                ..
321            } => cursor_watermark(
322                position,
323                CursorKind::Boundary,
324                cursor_position,
325                claimed_checkpoint,
326            ),
327            Self::CursorBound {
328                position,
329                cursor_position,
330                kind,
331            } => cursor_watermark(position, kind, cursor_position, covered_checkpoint_bound),
332            Self::ServingFloor {
333                position,
334                cursor_position,
335                floor_checkpoint,
336            } => cursor_watermark(
337                position,
338                CursorKind::Boundary,
339                cursor_position,
340                Some(floor_checkpoint),
341            ),
342        }
343    }
344}
345
346#[cfg(test)]
347mod tests {
348    use super::*;
349
350    use crate::ledger_history::query_options::assert_below_serving_floor_error;
351
352    fn options(ascending: bool) -> QueryOptions {
353        let mut request = sui_rpc::proto::sui::rpc::v2::QueryOptions::default();
354        request.ordering = Some(if ascending {
355            sui_rpc::proto::sui::rpc::v2::Ordering::Ascending as i32
356        } else {
357            sui_rpc::proto::sui::rpc::v2::Ordering::Descending as i32
358        });
359        QueryOptions::transactions_from_proto(Some(&request), 100, 100).unwrap()
360    }
361
362    #[test]
363    fn merge_covered_checkpoint_bound_keeps_most_advanced_in_direction() {
364        let asc = options(true);
365        assert_eq!(merge_covered_checkpoint_bound(None, 5, &asc), Some(5));
366        assert_eq!(merge_covered_checkpoint_bound(Some(5), 9, &asc), Some(9));
367        assert_eq!(merge_covered_checkpoint_bound(Some(9), 5, &asc), Some(9));
368
369        let desc = options(false);
370        assert_eq!(merge_covered_checkpoint_bound(None, 9, &desc), Some(9));
371        assert_eq!(merge_covered_checkpoint_bound(Some(9), 5, &desc), Some(5));
372        assert_eq!(merge_covered_checkpoint_bound(Some(5), 9, &desc), Some(5));
373    }
374
375    /// The per-checkpoint scanners exclude the item's own cp: `C - 1`
376    /// ascending, `C + 1` descending.
377    #[test]
378    fn advance_covered_bound_before_checkpoint_adjusts_by_one() {
379        let asc = options(true);
380        assert_eq!(
381            advance_covered_bound_before_checkpoint(None, 10, 5, &asc),
382            Some(9)
383        );
384        assert_eq!(
385            advance_covered_bound_before_checkpoint(Some(9), 12, 5, &asc),
386            Some(11)
387        );
388
389        let desc = options(false);
390        assert_eq!(
391            advance_covered_bound_before_checkpoint(None, 10, 15, &desc),
392            Some(11)
393        );
394        assert_eq!(
395            advance_covered_bound_before_checkpoint(Some(11), 8, 15, &desc),
396            Some(9)
397        );
398    }
399
400    /// A candidate before the entry checkpoint lies outside the window and is
401    /// discarded. The claim at exactly the entry checkpoint (candidate ==
402    /// entry) is the first legal one.
403    #[test]
404    fn advance_covered_bound_before_checkpoint_discards_candidates_outside_the_window() {
405        let asc = options(true);
406        assert_eq!(
407            advance_covered_bound_before_checkpoint(None, 10, 10, &asc),
408            None
409        );
410        assert_eq!(
411            advance_covered_bound_before_checkpoint(None, 11, 10, &asc),
412            Some(10)
413        );
414
415        let desc = options(false);
416        assert_eq!(
417            advance_covered_bound_before_checkpoint(None, 10, 10, &desc),
418            None
419        );
420        assert_eq!(
421            advance_covered_bound_before_checkpoint(None, 9, 10, &desc),
422            Some(10)
423        );
424    }
425
426    /// Overflow at the range edge (`cp 0` ascending, `u64::MAX` descending)
427    /// preserves the previously accumulated boundary instead of dropping it.
428    #[test]
429    fn advance_covered_bound_before_checkpoint_preserves_prev_on_overflow() {
430        let asc = options(true);
431        assert_eq!(
432            advance_covered_bound_before_checkpoint(Some(4), 0, 0, &asc),
433            Some(4)
434        );
435        assert_eq!(
436            advance_covered_bound_before_checkpoint(None, 0, 0, &asc),
437            None
438        );
439
440        let desc = options(false);
441        assert_eq!(
442            advance_covered_bound_before_checkpoint(Some(4), u64::MAX, u64::MAX, &desc),
443            Some(4)
444        );
445        assert_eq!(
446            advance_covered_bound_before_checkpoint(None, u64::MAX, u64::MAX, &desc),
447            None
448        );
449    }
450
451    #[test]
452    fn boundary_cursor_cp_bumps_descending_only() {
453        assert_eq!(boundary_cursor_cp(10, ScanDirection::Ascending), 10);
454        assert_eq!(boundary_cursor_cp(10, ScanDirection::Descending), 11);
455        assert_eq!(
456            boundary_cursor_cp(u64::MAX, ScanDirection::Descending),
457            u64::MAX
458        );
459    }
460
461    /// The direction-correct boundary is recorded in the single `checkpoint` field regardless of
462    /// ordering. A client reads the bound off the wire frame and interprets it per the request's
463    /// ordering. The resume point is above the item's key ascending, and the key descending; the
464    /// cursor carries the key either way.
465    #[test]
466    fn item_watermark_sets_direction_matching_bound_and_resume_point() {
467        let key = LedgerPoint::transaction(9, 3);
468        let pos = Position::Transactions {
469            tx_seq: 42,
470            public_position: key,
471        };
472        let cursor = CursorToken::item(pos).encode();
473        let wm = item_watermark(pos, ScanDirection::Ascending, Some(8));
474        assert_eq!(wm.checkpoint, Some(8));
475        assert_eq!(wm.cursor.as_ref(), Some(&cursor));
476        assert_eq!(
477            wm.cursor_position,
478            Some(LedgerPoint::transaction(9, 4).to_ledger_position(&pos))
479        );
480
481        let wm = item_watermark(pos, ScanDirection::Descending, None);
482        assert_eq!(wm.checkpoint, None);
483        assert_eq!(wm.cursor.as_ref(), Some(&cursor));
484        assert_eq!(wm.cursor_position, Some(key.to_ledger_position(&pos)));
485
486        // A checkpoint cursor's public position is its checkpoint's start.
487        let checkpoint = Position::Checkpoints { checkpoint: 9 };
488        let wm = item_watermark(checkpoint, ScanDirection::Ascending, Some(9));
489        assert_eq!(
490            wm.cursor.as_ref(),
491            Some(&CursorToken::item(checkpoint).encode())
492        );
493        assert_eq!(
494            wm.cursor_position,
495            Some(LedgerPoint::checkpoint_start(10).to_ledger_position(&checkpoint))
496        );
497        let wm = item_watermark(checkpoint, ScanDirection::Descending, None);
498        assert_eq!(
499            wm.cursor_position,
500            Some(LedgerPoint::checkpoint_start(9).to_ledger_position(&checkpoint))
501        );
502    }
503
504    #[test]
505    fn scan_terminal_converts_every_range_exhaustion() {
506        let position = Position::Transactions {
507            tx_seq: 4,
508            public_position: LedgerPoint::transaction(9, 1),
509        };
510        // A frame clamped past its cursor resumes at a point other than the cursor's own.
511        let cursor_position = LedgerPoint::transaction(9, 2);
512        let cases = [
513            (
514                RangeExhaustion::LedgerTip,
515                Some(8),
516                ScanTerminal::NaturalRange {
517                    end: NaturalRangeEnd::LedgerTip,
518                    position,
519                    cursor_position,
520                    claimed_checkpoint: Some(8),
521                },
522            ),
523            (
524                RangeExhaustion::CheckpointBound,
525                None,
526                ScanTerminal::NaturalRange {
527                    end: NaturalRangeEnd::CheckpointBound,
528                    position,
529                    cursor_position,
530                    claimed_checkpoint: None,
531                },
532            ),
533            (
534                RangeExhaustion::CursorBound {
535                    kind: CursorKind::Item,
536                },
537                Some(8),
538                ScanTerminal::CursorBound {
539                    position,
540                    cursor_position,
541                    kind: CursorKind::Item,
542                },
543            ),
544            (
545                RangeExhaustion::CursorBound {
546                    kind: CursorKind::Item,
547                },
548                None,
549                ScanTerminal::CursorBound {
550                    position,
551                    cursor_position,
552                    kind: CursorKind::Item,
553                },
554            ),
555            (
556                RangeExhaustion::ServingFloor {
557                    floor_checkpoint: 7,
558                },
559                Some(7),
560                ScanTerminal::ServingFloor {
561                    position,
562                    cursor_position,
563                    floor_checkpoint: 7,
564                },
565            ),
566        ];
567
568        for (exhaustion, claimed_checkpoint, expected) in cases {
569            let terminal = ScanTerminal::from_range_exhaustion(
570                exhaustion,
571                position,
572                cursor_position,
573                claimed_checkpoint,
574            );
575            assert_eq!(terminal, expected);
576            let watermark = terminal.into_watermark(Some(3));
577            assert_eq!(
578                watermark.cursor_position,
579                Some(cursor_position.to_ledger_position(&position))
580            );
581            let cursor = CursorToken::decode(&watermark.cursor.unwrap()).unwrap();
582            assert_eq!(
583                cursor.position.public_position(),
584                LedgerPoint::transaction(9, 1)
585            );
586        }
587    }
588
589    /// A serving-floor terminal renders a boundary cursor at the floor position claiming the floor
590    /// checkpoint, whatever coverage the items accumulated, and carries no `QueryEnd` reason: its
591    /// stream fails with `OutOfRange` instead.
592    #[test]
593    fn scan_terminal_serving_floor_claims_the_floor_and_fails_the_stream() {
594        let floor = LedgerPoint::checkpoint_start(7);
595        let position = Position::Transactions {
596            tx_seq: 35,
597            public_position: floor,
598        };
599        let terminal = ScanTerminal::ServingFloor {
600            position,
601            cursor_position: floor,
602            floor_checkpoint: 7,
603        };
604
605        let error = terminal
606            .reason()
607            .expect_err("a serving floor ends with no QueryEnd");
608        assert_below_serving_floor_error(error, 7);
609
610        for covered_checkpoint_bound in [None, Some(9)] {
611            let watermark = terminal.clone().into_watermark(covered_checkpoint_bound);
612            assert_eq!(
613                watermark.cursor,
614                Some(CursorToken::boundary(position).encode())
615            );
616            assert_eq!(watermark.checkpoint, Some(7));
617            assert_eq!(
618                watermark.cursor_position,
619                Some(floor.to_ledger_position(&position))
620            );
621        }
622    }
623
624    /// A natural end claims its `claimed_checkpoint` behind a boundary cursor at its position,
625    /// whatever coverage the items accumulated.
626    #[test]
627    fn scan_terminal_natural_range_claims_its_claimed_checkpoint() {
628        let position = Position::Transactions {
629            tx_seq: 4,
630            public_position: LedgerPoint::transaction(9, 0),
631        };
632
633        for claimed_checkpoint in [8, 9] {
634            let checkpoint_bound = ScanTerminal::NaturalRange {
635                end: NaturalRangeEnd::CheckpointBound,
636                position,
637                cursor_position: position.public_position(),
638                claimed_checkpoint: Some(claimed_checkpoint),
639            };
640            assert_eq!(
641                checkpoint_bound.reason().unwrap(),
642                QueryEndReason::CheckpointBound
643            );
644            let watermark = checkpoint_bound.into_watermark(None);
645            assert_eq!(
646                watermark.cursor,
647                Some(CursorToken::boundary(position).encode())
648            );
649            assert_eq!(watermark.checkpoint, Some(claimed_checkpoint));
650
651            let ledger_tip = ScanTerminal::NaturalRange {
652                end: NaturalRangeEnd::LedgerTip,
653                position,
654                cursor_position: position.public_position(),
655                claimed_checkpoint: Some(claimed_checkpoint),
656            };
657            assert_eq!(ledger_tip.reason().unwrap(), QueryEndReason::LedgerTip);
658            let watermark = ledger_tip.into_watermark(Some(6));
659            assert_eq!(
660                watermark.cursor,
661                Some(CursorToken::boundary(position).encode())
662            );
663            assert_eq!(watermark.checkpoint, Some(claimed_checkpoint));
664        }
665    }
666
667    /// A natural end with no claimed checkpoint (its window has no checkpoint this server
668    /// serves) keeps its terminal cursor and leaves the checkpoint claim unset, for both natural
669    /// reasons and whatever coverage the items accumulated.
670    #[test]
671    fn scan_terminal_unclaimed_natural_end_claims_nothing() {
672        let position = Position::Transactions {
673            tx_seq: 4,
674            public_position: LedgerPoint::transaction(9, 0),
675        };
676
677        for (end, reason) in [
678            (
679                NaturalRangeEnd::CheckpointBound,
680                QueryEndReason::CheckpointBound,
681            ),
682            (NaturalRangeEnd::LedgerTip, QueryEndReason::LedgerTip),
683        ] {
684            let terminal = ScanTerminal::NaturalRange {
685                end,
686                position,
687                cursor_position: position.public_position(),
688                claimed_checkpoint: None,
689            };
690            assert_eq!(terminal.reason().unwrap(), reason);
691            let watermark = terminal.clone().into_watermark(None);
692            assert_eq!(
693                watermark.cursor,
694                Some(CursorToken::boundary(position).encode())
695            );
696            assert_eq!(watermark.checkpoint, None);
697            let watermark = terminal.into_watermark(Some(6));
698            assert_eq!(
699                watermark.cursor,
700                Some(CursorToken::boundary(position).encode())
701            );
702            assert_eq!(watermark.checkpoint, None);
703        }
704    }
705
706    #[test]
707    fn scan_terminal_cursor_bound_preserves_coverage() {
708        let position = Position::Transactions {
709            tx_seq: 4,
710            public_position: LedgerPoint::transaction(9, 0),
711        };
712        let terminal = ScanTerminal::CursorBound {
713            position,
714            cursor_position: position.public_position(),
715            kind: CursorKind::Boundary,
716        };
717        assert_eq!(terminal.reason().unwrap(), QueryEndReason::CursorBound);
718
719        let watermark = terminal.clone().into_watermark(Some(6));
720        assert_eq!(
721            watermark.cursor,
722            Some(CursorToken::boundary(position).encode())
723        );
724        assert_eq!(watermark.checkpoint, Some(6));
725
726        let watermark = terminal.into_watermark(None);
727        assert_eq!(
728            watermark.cursor,
729            Some(CursorToken::boundary(position).encode())
730        );
731        assert_eq!(watermark.checkpoint, None);
732    }
733
734    #[test]
735    fn scan_terminal_event_cursor_bound_preserves_item_kind() {
736        let position = Position::Events {
737            tx_seq: 4,
738            event_index: 2,
739            public_position: LedgerPoint::event(9, 0, 2),
740        };
741        let terminal = ScanTerminal::CursorBound {
742            position,
743            cursor_position: position.public_position(),
744            kind: CursorKind::Item,
745        };
746        assert_eq!(terminal.reason().unwrap(), QueryEndReason::CursorBound);
747
748        let watermark = terminal.into_watermark(Some(6));
749        assert_eq!(watermark.cursor, Some(CursorToken::item(position).encode()));
750        assert_eq!(watermark.checkpoint, Some(6));
751    }
752
753    #[test]
754    fn scan_terminal_scan_limit_returns_owned_watermark() {
755        let mut watermark = Watermark::default();
756        watermark.cursor = Some(b"scan-limit".to_vec().into());
757        watermark.checkpoint = Some(6);
758        let terminal = ScanTerminal::ScanLimit {
759            watermark: watermark.clone(),
760        };
761        assert_eq!(terminal.reason().unwrap(), QueryEndReason::ScanLimit);
762        assert_eq!(terminal.into_watermark(None), watermark);
763
764        let terminal = ScanTerminal::ScanLimit {
765            watermark: watermark.clone(),
766        };
767        assert_eq!(terminal.into_watermark(Some(99)), watermark);
768    }
769}