1use crate::{CoreError, Result};
11
12pub const DEFAULT_LIST_LIMIT: u32 = 1000;
16
17#[derive(Debug, Clone, PartialEq, Eq)]
23#[non_exhaustive]
24pub struct Paged<T> {
25 pub items: Vec<T>,
27 pub truncated: bool,
29 pub limit: u32,
31}
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum FetchStrategy {
38 SingleShot,
42 Paged {
46 per_page: u32,
48 },
49}
50
51async fn fetch_all_pages<T, F, Fut>(per_page: u32, want: usize, fetch: &F) -> Result<Vec<T>>
63where
64 F: Fn(u32, u32) -> Fut,
65 Fut: std::future::Future<Output = Result<Vec<T>>>,
66{
67 if per_page == 0 {
68 return Err(CoreError::Platform(
69 "pagination per_page must be greater than zero".to_string(),
70 ));
71 }
72 let mut items: Vec<T> = Vec::new();
73 let mut page: u32 = 1;
74 loop {
75 let batch = fetch(page, per_page).await?;
76 let batch_len = batch.len();
77 items.extend(batch);
78
79 let per_page_usize = usize::try_from(per_page).unwrap_or(usize::MAX);
81 if batch_len < per_page_usize {
82 break; }
84 if items.len() >= want {
85 break; }
87 page = page
88 .checked_add(1)
89 .ok_or_else(|| CoreError::Platform("pagination page number overflowed".to_string()))?;
90 }
91 Ok(items)
92}
93
94pub async fn fetch_capped<T, F, Fut>(
152 strategy: FetchStrategy,
153 cap: u32,
154 fetch: F,
155) -> Result<Paged<T>>
156where
157 F: Fn(u32, u32) -> Fut,
158 Fut: std::future::Future<Output = Result<Vec<T>>>,
159{
160 let want = usize::try_from(cap.saturating_add(1)).unwrap_or(usize::MAX);
162
163 let mut items: Vec<T> = match strategy {
164 FetchStrategy::SingleShot => {
165 let limit = cap.saturating_add(1);
166 fetch(1, limit).await?
167 }
168 FetchStrategy::Paged { per_page } => fetch_all_pages(per_page, want, &fetch).await?,
169 };
170
171 let cap_usize = usize::try_from(cap).unwrap_or(usize::MAX);
173 let truncated = items.len() > cap_usize;
174 if truncated {
175 items.truncate(cap_usize);
176 }
177
178 Ok(Paged {
179 items,
180 truncated,
181 limit: cap,
182 })
183}
184
185impl<T> Paged<T> {
186 #[must_use]
191 pub fn into_parts(self) -> (Vec<T>, crate::output::PaginationMeta) {
192 let meta = crate::output::PaginationMeta {
193 truncated: self.truncated,
194 returned: self.items.len(),
195 limit: self.limit,
196 };
197 (self.items, meta)
198 }
199}
200
201#[cfg(test)]
202mod tests {
203 use std::sync::Mutex;
204
205 use super::*;
206
207 #[derive(Debug)]
209 struct Source {
210 total: usize,
211 calls: Mutex<Vec<(u32, u32)>>,
212 }
213
214 impl Source {
215 fn new(total: usize) -> Self {
216 Self {
217 total,
218 calls: Mutex::new(Vec::new()),
219 }
220 }
221
222 fn page(&self, page: u32, limit: u32) -> Vec<usize> {
224 if let Ok(mut calls) = self.calls.lock() {
225 calls.push((page, limit));
226 }
227 let start = (page as usize - 1) * limit as usize;
228 if start >= self.total {
229 return Vec::new();
230 }
231 let end = std::cmp::min(start + limit as usize, self.total);
232 (start..end).collect()
233 }
234
235 fn recorded(&self) -> Vec<(u32, u32)> {
236 self.calls.lock().map(|c| c.clone()).unwrap_or_default()
237 }
238 }
239
240 async fn run_single_shot(total: usize, cap: u32) -> (Paged<usize>, Vec<(u32, u32)>) {
241 let src = Source::new(total);
242 let paged = fetch_capped(FetchStrategy::SingleShot, cap, |page, limit| {
243 let src = &src;
244 async move { Ok(src.page(page, limit)) }
245 })
246 .await
247 .expect("fetch_capped should succeed");
248 let calls = src.recorded();
249 (paged, calls)
250 }
251
252 async fn run_paged(total: usize, cap: u32, per_page: u32) -> (Paged<usize>, Vec<(u32, u32)>) {
253 let src = Source::new(total);
254 let paged = fetch_capped(FetchStrategy::Paged { per_page }, cap, |page, limit| {
255 let src = &src;
256 async move { Ok(src.page(page, limit)) }
257 })
258 .await
259 .expect("fetch_capped should succeed");
260 let calls = src.recorded();
261 (paged, calls)
262 }
263
264 #[tokio::test]
265 async fn test_should_request_cap_plus_one_in_single_shot() {
266 let (_, calls) = run_single_shot(5, 10).await;
267 assert_eq!(calls, vec![(1, 11)], "single-shot 必须一次要 cap+1 条");
268 }
269
270 #[tokio::test]
271 async fn test_should_not_truncate_when_total_below_cap() {
272 let (paged, _) = run_single_shot(5, 10).await;
273 assert_eq!(paged.items.len(), 5);
274 assert!(!paged.truncated);
275 assert_eq!(paged.limit, 10);
276 }
277
278 #[tokio::test]
279 async fn test_should_not_truncate_when_total_equals_cap() {
280 let (paged, _) = run_single_shot(10, 10).await;
281 assert_eq!(paged.items.len(), 10);
282 assert!(!paged.truncated, "恰好 cap 条不算截断");
283 }
284
285 #[tokio::test]
286 async fn test_should_truncate_when_total_exceeds_cap_by_one() {
287 let (paged, _) = run_single_shot(11, 10).await;
288 assert_eq!(paged.items.len(), 10, "超出部分必须被截掉");
289 assert!(paged.truncated, "N+1 探测必须发现还有更多");
290 }
291
292 #[tokio::test]
293 async fn test_should_truncate_when_total_far_exceeds_cap() {
294 let (paged, _) = run_single_shot(500, 10).await;
295 assert_eq!(paged.items.len(), 10);
296 assert!(paged.truncated);
297 }
298
299 #[tokio::test]
300 async fn test_should_return_empty_without_truncation_when_source_empty() {
301 let (paged, _) = run_single_shot(0, 10).await;
302 assert!(paged.items.is_empty());
303 assert!(!paged.truncated);
304 }
305
306 #[tokio::test]
307 async fn test_should_stop_paging_on_short_page() {
308 let (paged, calls) = run_paged(5, 100, 10).await;
310 assert_eq!(paged.items.len(), 5);
311 assert!(!paged.truncated);
312 assert_eq!(calls, vec![(1, 10)], "短页即取尽,不得再请求第 2 页");
313 }
314
315 #[tokio::test]
316 async fn test_should_walk_pages_until_cap_plus_one_collected() {
317 let (paged, calls) = run_paged(100, 25, 10).await;
319 assert_eq!(paged.items.len(), 25);
320 assert!(paged.truncated);
321 assert_eq!(calls, vec![(1, 10), (2, 10), (3, 10)]);
322 }
323
324 #[tokio::test]
325 async fn test_should_probe_one_past_cap_when_cap_is_a_multiple_of_per_page() {
326 let (paged, calls) = run_paged(30, 20, 10).await;
330 assert_eq!(
331 calls,
332 vec![(1, 10), (2, 10), (3, 10)],
333 "必须探到第 3 页才能发现还有更多"
334 );
335 assert_eq!(paged.items.len(), 20);
336 assert!(paged.truncated, "30 > cap=20,必须报告截断");
337 }
338
339 #[tokio::test]
340 async fn test_should_stop_paging_when_exhausted_exactly_at_page_boundary() {
341 let (paged, calls) = run_paged(20, 100, 10).await;
343 assert_eq!(paged.items.len(), 20);
344 assert!(!paged.truncated);
345 assert_eq!(calls, vec![(1, 10), (2, 10), (3, 10)]);
346 }
347
348 #[tokio::test]
349 async fn test_should_preserve_item_order_across_pages() {
350 let (paged, _) = run_paged(25, 100, 10).await;
351 assert_eq!(paged.items, (0..25).collect::<Vec<usize>>());
352 }
353
354 #[tokio::test]
355 async fn test_should_reject_zero_per_page() {
356 let src = Source::new(10);
357 let result = fetch_capped(FetchStrategy::Paged { per_page: 0 }, 10, |page, limit| {
358 let src = &src;
359 async move { Ok(src.page(page, limit)) }
360 })
361 .await;
362 assert!(
363 matches!(result, Err(CoreError::Platform(_))),
364 "per_page = 0 会导致死循环,必须直接报错"
365 );
366 }
367
368 #[tokio::test]
369 async fn test_should_propagate_fetch_error() {
370 let result: Result<Paged<usize>> =
371 fetch_capped(FetchStrategy::SingleShot, 10, async |_page, _limit| {
372 Err(CoreError::Platform("boom".to_string()))
373 })
374 .await;
375 assert!(matches!(result, Err(CoreError::Platform(msg)) if msg == "boom"));
376 }
377
378 #[tokio::test]
379 async fn test_should_return_empty_and_truncated_when_cap_is_zero() {
380 let (paged, _) = run_single_shot(5, 0).await;
381 assert!(paged.items.is_empty());
382 assert!(paged.truncated, "cap=0 但源里有数据,必须诚实报告截断");
383 }
384
385 #[test]
386 fn test_should_expose_default_list_limit_of_1000() {
387 assert_eq!(DEFAULT_LIST_LIMIT, 1000);
388 }
389}