sms_client/http/
paginator.rs

1//! HTTP request paginator, supporting lazy traversal across large sets
2
3use crate::http::error::HttpResult;
4use crate::http::types::HttpPaginationOptions;
5
6/// Call a function with an update `HttpPaginationOptions` for each batch request,
7/// simplifying lazy access to large response sets such as messages etc.
8pub struct HttpPaginator<T, F, Fut> {
9    http_fn: F,
10    pagination: HttpPaginationOptions,
11    current_batch: Vec<T>,
12    current_index: usize,
13    has_more: bool,
14    initial_limit: u64,
15    _phantom: std::marker::PhantomData<Fut>,
16}
17impl<T, F, Fut> HttpPaginator<T, F, Fut>
18where
19    F: Fn(Option<HttpPaginationOptions>) -> Fut,
20    Fut: Future<Output = HttpResult<Vec<T>>>,
21{
22    /// Create the paginator with the http batch generator.
23    ///
24    /// # Example
25    /// ```text
26    /// use sms_client::Client;
27    /// use sms_client::config::ClientConfig;
28    /// use sms_client::http::paginator::HttpPaginator;
29    /// use sms_client::http::types::HttpPaginationOptions;
30    ///
31    /// let http = Client::new(ClientConfig::http_only("http://localhost:3000").with_auth("token!"))?.http_arc();
32    /// let mut paginator = HttpPaginator::new(
33    ///     move |pagination| {
34    ///         let http = http.expect("Missing HTTP client configuration!").clone();
35    ///         async move {
36    ///             http.get_latest_numbers(pagination).await
37    ///         }
38    ///     },
39    ///     HttpPaginationOptions::default()
40    ///         .with_limit(10) // Do it in batches of 10.
41    ///         .with_offset(10) // Skip the first 10 results.
42    ///         .with_reverse(true) // Reverse the results set.
43    /// );
44    /// ```
45    pub fn new(http_fn: F, pagination: HttpPaginationOptions) -> Self {
46        let initial_limit = pagination.limit.unwrap_or(50);
47
48        Self {
49            http_fn,
50            pagination,
51            current_batch: Vec::new(),
52            current_index: 0,
53            has_more: true,
54            initial_limit,
55            _phantom: std::marker::PhantomData,
56        }
57    }
58
59    /// Create a paginator with default pagination settings.
60    /// This starts at offset 0 with a limit of 50 per page.
61    ///
62    /// # Example
63    /// ```text
64    /// use sms_client::http;
65    /// use sms_client::Client;
66    /// use sms_client::config::ClientConfig;
67    /// use sms_client::http::HttpClient;
68    /// use sms_client::http::paginator::HttpPaginator;
69    ///
70    /// /// View all latest numbers, in a default paginator with a limit of 50 per chunk.
71    /// async fn view_all_latest_numbers(http: HttpClient) {
72    ///     let mut paginator = HttpPaginator::with_defaults(|pagination| {
73    ///         http.get_latest_numbers(pagination)
74    ///     });
75    ///     while let Some(message) = paginator.next().await {
76    ///         log::info!("{:?}", message);
77    ///     }
78    /// }
79    /// ```
80    pub fn with_defaults(http_fn: F) -> Self {
81        Self::new(
82            http_fn,
83            HttpPaginationOptions::default()
84                .with_limit(50)
85                .with_offset(0),
86        )
87    }
88
89    /// Fetch the next batch of items from the API.
90    async fn fetch_next_batch(&mut self) -> HttpResult<bool> {
91        let response = (self.http_fn)(Some(self.pagination)).await?;
92
93        let received_count = response.len() as u64;
94        self.has_more = received_count >= self.initial_limit;
95
96        // If no more items have been received, we're definitely done.
97        if received_count == 0 {
98            self.has_more = false;
99            return Ok(false);
100        }
101
102        self.current_batch = response;
103        self.current_index = 0;
104
105        // Update offset for next request.
106        if let Some(current_offset) = self.pagination.offset {
107            self.pagination.offset = Some(current_offset + received_count);
108        } else {
109            // If no offset was set initially, start from the received count
110            self.pagination.offset = Some(received_count);
111        }
112
113        Ok(true)
114    }
115
116    /// Get the next item, automatically fetching next pages as needed.
117    ///
118    /// # Example
119    /// ```text
120    /// use sms_client::http::HttpClient;
121    /// use sms_client::http::paginator::HttpPaginator;
122    ///
123    /// async fn get_delivery_reports(message_id: i64, http: HttpClient) {
124    ///     let mut paginator = HttpPaginator::with_defaults(|pagination| {
125    ///         http.get_delivery_reports(message_id, pagination)
126    ///     }).await;
127    ///
128    ///     /// Iterate through ALL messages, with a page size of 50 (default).
129    ///     while let Some(message) = paginator.next().await {
130    ///         log::info!("{:?}", message);
131    ///     }
132    /// }
133    /// ```
134    pub async fn next(&mut self) -> Option<T> {
135        if self.current_index >= self.current_batch.len() {
136            // If there aren't any-more, then there is nothing to fetch next.
137            if !self.has_more {
138                return None;
139            }
140
141            match self.fetch_next_batch().await {
142                Ok(true) => {}                     // Successfully fetched more data
143                Ok(false) | Err(_) => return None, // No more data or error
144            }
145        }
146
147        // Return the next item if available.
148        if self.current_index < self.current_batch.len() {
149            let item = self.current_batch.remove(0);
150            Some(item)
151        } else {
152            None
153        }
154    }
155
156    /// Collect all remaining items into a Vec.
157    /// This continues to request batches until empty.
158    pub async fn collect_all(mut self) -> HttpResult<Vec<T>> {
159        let mut all_items = Vec::new();
160
161        if self.current_batch.is_empty() && self.has_more {
162            self.fetch_next_batch().await?;
163        }
164
165        while let Some(item) = self.next().await {
166            all_items.push(item);
167        }
168
169        Ok(all_items)
170    }
171
172    /// Process items in chunks, calling the provided closure for each chunk.
173    pub async fn take(mut self, n: usize) -> HttpResult<Vec<T>> {
174        let mut items = Vec::with_capacity(n.min(100)); // Cap initial capacity
175
176        for _ in 0..n {
177            if let Some(item) = self.next().await {
178                items.push(item);
179            } else {
180                break;
181            }
182        }
183
184        Ok(items)
185    }
186
187    /// Process items in chunks, calling the provided closure for each chunk.
188    ///
189    /// # Example
190    /// ```text
191    /// use std::sync::Arc;
192    /// use sms_client::http::HttpClient;
193    /// use sms_client::http::paginator::HttpPaginator;
194    /// use sms_client::http::types::HttpPaginationOptions;
195    ///
196    /// /// Read all messages from a phone number, in chunks of 10.
197    /// async fn read_all_messages(phone_number: &str, http: Arc<HttpClient>) {
198    ///     let paginator = HttpPaginator::with_defaults(|pagination| {
199    ///         http.get_messages(phone_number, pagination)
200    ///     }).await;
201    ///
202    ///     paginator.for_each_chuck(10, |batch| {
203    ///         for message in batch {
204    ///             log::info!("{:?}", message);
205    ///         }
206    ///     }).await?;
207    /// }
208    /// ```
209    pub async fn for_each_chuck<C>(mut self, chunk_size: usize, mut chunk_fn: C) -> HttpResult<()>
210    where
211        C: FnMut(&[T]) -> HttpResult<()>,
212    {
213        let mut chunk = Vec::with_capacity(chunk_size);
214
215        while let Some(item) = self.next().await {
216            chunk.push(item);
217
218            if chunk.len() >= chunk_size {
219                chunk_fn(&chunk)?;
220                chunk.clear();
221            }
222        }
223
224        // Process any remaining items in the final chunk.
225        if !chunk.is_empty() {
226            chunk_fn(&chunk)?;
227        }
228
229        Ok(())
230    }
231
232    /// Skip `n` items and return the paginator.
233    pub async fn skip(mut self, n: usize) -> Self {
234        for _ in 0..n {
235            if self.next().await.is_none() {
236                break;
237            }
238        }
239        self
240    }
241
242    /// Get the current pagination options state.
243    pub fn current_pagination(&self) -> &HttpPaginationOptions {
244        &self.pagination
245    }
246
247    /// Check if there are potentially more items to fetch.
248    pub fn has_more(&self) -> bool {
249        self.has_more || self.current_index < self.current_batch.len()
250    }
251}