Skip to main content

libtea_client/
page_stream.rs

1//! Opt-in pagination helpers.
2//!
3//! **Experimental:** may change in a 0.x minor release.
4//!
5//! The primary API remains caller-managed [`libtea_core::ListParams`]: replace
6//! only `page_token` between calls. These helpers follow `next_page_token` with
7//! hard limits so a hostile or buggy server cannot force unbounded fetches.
8
9use std::future::Future;
10use std::pin::Pin;
11
12use futures_util::stream::{self, Stream};
13use libtea_core::{ListParams, Page};
14
15use crate::error::ClientError;
16
17/// Limits for automatic page following.
18///
19/// **Experimental:** may change in a 0.x minor release.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21#[non_exhaustive]
22pub struct PageFollowLimits {
23    /// Maximum number of HTTP list pages to fetch (including the first).
24    pub max_pages: u32,
25    /// Stop after the page on which the running item count reaches this value.
26    ///
27    /// That page is yielded whole, so the total can exceed this by up to one
28    /// page (each page is still bounded by [`crate::Limits::max_json_bytes`]).
29    pub max_items: u64,
30}
31
32impl Default for PageFollowLimits {
33    fn default() -> Self {
34        Self {
35            max_pages: 32,
36            max_items: 10_000,
37        }
38    }
39}
40
41/// Why page following stopped.
42///
43/// **Experimental:** may change in a 0.x minor release.
44#[derive(Debug, Clone, PartialEq, Eq)]
45#[non_exhaustive]
46pub enum PageFollowStop {
47    /// Server reported no further page (`has_next` false or empty token).
48    Exhausted,
49    /// Hit [`PageFollowLimits::max_pages`].
50    MaxPages,
51    /// Hit [`PageFollowLimits::max_items`].
52    MaxItems,
53    /// Server repeated the same `next_page_token` (loop guard).
54    RepeatedToken,
55}
56
57/// One page in a followed list, plus whether following should continue.
58///
59/// **Experimental:** may change in a 0.x minor release.
60#[derive(Debug)]
61#[non_exhaustive]
62pub struct FollowedPage<T> {
63    /// Decoded page body.
64    pub page: Page<T>,
65    /// Why this was the last page, if following stopped.
66    pub stop: Option<PageFollowStop>,
67}
68
69impl PageFollowLimits {
70    /// Limits with an explicit page and item bound.
71    #[must_use]
72    pub fn new(max_pages: u32, max_items: u64) -> Self {
73        Self {
74            max_pages,
75            max_items,
76        }
77    }
78
79    /// Set [`Self::max_pages`].
80    #[must_use]
81    pub fn with_max_pages(mut self, max_pages: u32) -> Self {
82        self.max_pages = max_pages;
83        self
84    }
85
86    /// Set [`Self::max_items`].
87    #[must_use]
88    pub fn with_max_items(mut self, max_items: u64) -> Self {
89        self.max_items = max_items;
90        self
91    }
92}
93
94type PageFuture<T> = Pin<Box<dyn Future<Output = Result<Page<T>, ClientError>> + Send>>;
95
96/// Follow `page_token` until exhausted or a limit / loop is hit.
97///
98/// **Experimental:** may change in a 0.x minor release.
99///
100/// `fetch` receives the current [`ListParams`] (caller should keep filters and
101/// replace only the token the helper sets). `S` is the list endpoint's sort
102/// type (for example `ProductSort`).
103pub fn follow_pages<T, S, F>(
104    params: ListParams<S>,
105    limits: PageFollowLimits,
106    fetch: F,
107) -> impl Stream<Item = Result<FollowedPage<T>, ClientError>>
108where
109    T: Send + 'static,
110    S: Clone + Send + 'static,
111    F: FnMut(ListParams<S>) -> PageFuture<T> + Send + 'static,
112{
113    stream::unfold(
114        FollowState {
115            params,
116            limits,
117            pages: 0,
118            items: 0,
119            last_token: None,
120            done: false,
121            fetch,
122        },
123        |mut state| async move {
124            if state.done {
125                return None;
126            }
127            if state.pages >= state.limits.max_pages {
128                return None;
129            }
130            let page = match (state.fetch)(state.params.clone()).await {
131                Ok(page) => page,
132                Err(error) => {
133                    state.done = true;
134                    return Some((Err(error), state));
135                }
136            };
137            state.pages += 1;
138            state.items = state.items.saturating_add(page.results.len() as u64);
139
140            let mut stop = None;
141            if state.items >= state.limits.max_items {
142                stop = Some(PageFollowStop::MaxItems);
143                state.done = true;
144            } else if state.pages >= state.limits.max_pages {
145                stop = Some(PageFollowStop::MaxPages);
146                state.done = true;
147            } else if !page.has_next {
148                stop = Some(PageFollowStop::Exhausted);
149                state.done = true;
150            } else {
151                match page.next_page_token.clone() {
152                    // An empty token cannot select a next page; following it
153                    // would re-request the first page.
154                    Some(token) if token.is_empty() => {
155                        stop = Some(PageFollowStop::Exhausted);
156                        state.done = true;
157                    }
158                    Some(token) if state.last_token.as_ref() == Some(&token) => {
159                        stop = Some(PageFollowStop::RepeatedToken);
160                        state.done = true;
161                    }
162                    Some(token) => {
163                        state.last_token = Some(token.clone());
164                        state.params.page_token = Some(token);
165                    }
166                    None => {
167                        stop = Some(PageFollowStop::Exhausted);
168                        state.done = true;
169                    }
170                }
171            }
172
173            Some((
174                Ok(FollowedPage {
175                    page,
176                    stop: if state.done {
177                        stop.or(Some(PageFollowStop::Exhausted))
178                    } else {
179                        None
180                    },
181                }),
182                state,
183            ))
184        },
185    )
186}
187
188struct FollowState<S, F> {
189    params: ListParams<S>,
190    limits: PageFollowLimits,
191    pages: u32,
192    items: u64,
193    last_token: Option<String>,
194    done: bool,
195    fetch: F,
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201    use futures_util::StreamExt;
202
203    #[tokio::test]
204    async fn stops_on_repeated_token() {
205        let stream = follow_pages(
206            ListParams::<()>::default(),
207            PageFollowLimits::default(),
208            |_: ListParams<()>| {
209                Box::pin(async { Ok(Page::new(vec![1_u32], true, Some("same".into()))) })
210            },
211        );
212        futures_util::pin_mut!(stream);
213        let first = stream.next().await.unwrap().unwrap();
214        assert!(first.stop.is_none());
215        let second = stream.next().await.unwrap().unwrap();
216        assert_eq!(second.stop, Some(PageFollowStop::RepeatedToken));
217        assert!(stream.next().await.is_none());
218    }
219
220    #[tokio::test]
221    async fn respects_max_pages() {
222        let limits = PageFollowLimits {
223            max_pages: 2,
224            max_items: 10_000,
225        };
226        let stream = follow_pages(ListParams::<()>::default(), limits, |_: ListParams<()>| {
227            Box::pin(async {
228                Ok(Page::new(
229                    vec![1_u32],
230                    true,
231                    Some(format!("{}", uuid_like())),
232                ))
233            })
234        });
235        futures_util::pin_mut!(stream);
236        assert!(stream.next().await.unwrap().unwrap().stop.is_none());
237        let last = stream.next().await.unwrap().unwrap();
238        assert_eq!(last.stop, Some(PageFollowStop::MaxPages));
239        assert!(stream.next().await.is_none());
240    }
241
242    #[tokio::test]
243    async fn empty_next_token_is_exhausted_not_followed() {
244        let calls = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
245        let counter = std::sync::Arc::clone(&calls);
246        let stream = follow_pages(
247            ListParams::<()>::default(),
248            PageFollowLimits::default(),
249            move |_: ListParams<()>| {
250                counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
251                Box::pin(async { Ok(Page::new(vec![1_u32], true, Some(String::new()))) })
252            },
253        );
254        futures_util::pin_mut!(stream);
255        let only = stream.next().await.unwrap().unwrap();
256        assert_eq!(only.stop, Some(PageFollowStop::Exhausted));
257        assert!(stream.next().await.is_none());
258        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
259    }
260
261    fn uuid_like() -> u64 {
262        use std::sync::atomic::{AtomicU64, Ordering};
263        static N: AtomicU64 = AtomicU64::new(1);
264        N.fetch_add(1, Ordering::Relaxed)
265    }
266}