Skip to main content

gitflow_core/
paging.rs

1//! 列表分页原语。
2//!
3//! 底层平台 CLI 的列表命令默认只返回首页(通常 30 条)且不给任何截断信号,
4//! 调用方无从判断拿到的是全集还是首页。本模块提供统一的「取到上限为止 +
5//! 触顶时诚实上报」语义。
6//!
7//! 上限不是设计偏好而是硬约束:`gh` 没有「无限」选项,`--limit` 只能是一个
8//! 具体数字,因此全量必然有界,有界就必须能被发现。
9
10use crate::{CoreError, Result};
11
12/// 列表命令默认抓取的条目上限。
13///
14/// 超过此数时结果被截断,且 [`Paged::truncated`] 置为 `true`。
15pub const DEFAULT_LIST_LIMIT: u32 = 1000;
16
17/// 一次分页抓取的结果。
18///
19/// 这是 provider trait 的内部返回类型,**不实现 `Serialize`**:CLI 层在输出前
20/// 会把它拆成纯数组(落到 `data`)与元数据(落到输出信封的 `pagination`),
21/// 以保证 `data` 的形状不因本特性而改变。
22#[derive(Debug, Clone, PartialEq, Eq)]
23#[non_exhaustive]
24pub struct Paged<T> {
25    /// 已截断到上限之内的条目,顺序与平台返回顺序一致。
26    pub items: Vec<T>,
27    /// 是否因触顶而丢弃了更多条目。由 N+1 探测得出,而非推测。
28    pub truncated: bool,
29    /// 本次生效的上限。
30    pub limit: u32,
31}
32
33/// 平台的分页能力。
34///
35/// 用枚举显式表达,而非靠算术巧合让循环在单次取满的平台上恰好只跑一轮。
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum FetchStrategy {
38    /// 底层 CLI 自行翻页,一次调用即可取至多 N 条。
39    ///
40    /// `gh`(`--limit`)与 gitcode(`--limit`)适用。
41    SingleShot,
42    /// 必须由调用方逐页请求,每页至多 `per_page` 条。
43    ///
44    /// `glab` 适用:其 `--per-page` 受 GitLab API 限制,上限 100。
45    Paged {
46        /// 每页条数,必须大于 0。
47        per_page: u32,
48    },
49}
50
51/// 按 [`FetchStrategy::Paged`] 逐页抓取,直到取够 `want` 条或页面取尽。
52///
53/// 只负责翻页循环本身:不做上限截断(由调用方 `fetch_capped` 统一处理),
54/// 输入输出与被提炼前的 `match` 分支完全一致(`per_page`/`want`/`fetch` →
55/// 收集到的条目)。
56///
57/// # Errors
58///
59/// - `per_page` 为 0 时返回 [`CoreError::Platform`]:该取值会导致翻页永不前进。
60/// - `fetch` 返回的错误原样透传。
61/// - 页号溢出 `u32` 时返回 [`CoreError::Platform`]。
62async 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        // Lossless on all supported 32/64-bit platforms: u32::MAX always fits in usize.
80        let per_page_usize = usize::try_from(per_page).unwrap_or(usize::MAX);
81        if batch_len < per_page_usize {
82            break; // 短页 ⇒ 已取尽
83        }
84        if items.len() >= want {
85            break; // 已够 N+1 探测所需
86        }
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
94/// 按 `strategy` 抓取至多 `cap` 条,并诚实报告是否还有更多。
95///
96/// 内部向下游请求 `cap + 1` 条(N+1 探测):只要 `cap` 条时无法区分
97/// 「恰好 cap 条」与「还有更多」。收到多于 `cap` 条即截断并置
98/// [`Paged::truncated`]。
99///
100/// `fetch` 的两个参数是 `(page, limit)`:
101/// - [`FetchStrategy::SingleShot`]:`page` 恒为 1,`limit` 为 `cap + 1`。
102/// - [`FetchStrategy::Paged`]:`page` 从 1 递增,`limit` 为 `per_page`。
103///
104/// # Errors
105///
106/// - `fetch` 返回的错误原样透传。
107/// - [`FetchStrategy::Paged`] 的 `per_page` 为 0 时返回
108///   [`CoreError::Platform`]:该取值会导致翻页永不前进。
109/// - 页号溢出 `u32` 时返回 [`CoreError::Platform`]。
110///
111/// `fetch` 是返回 `Future` 的普通闭包(`Fn(u32, u32) -> Fut`),而非原生
112/// `AsyncFn`:在 `#[async_trait]` 装箱的方法体内调用一个捕获引用的
113/// `async move |..| {..}` 闭包会触发 rustc 的 HRTB `Send` 检查缺陷
114/// (`implementation of Send is not general enough`)。返回具名 `Future` 的
115/// 普通闭包不受此限制影响。
116///
117/// # Examples
118///
119/// 从一个自身借用了 `self` 字段的方法体里调用时,**借用**要捕获的字段
120/// (而非 `.clone()` 后 `move` 进闭包),再让每次调用返回的 `async move`
121/// 块去移动那个借用——借用是 `Copy`,因此闭包仍满足 `Fn`:
122///
123/// ```
124/// use gitflow_core::{FetchStrategy, Result, fetch_capped};
125///
126/// struct Source {
127///     repo: String,
128/// }
129///
130/// impl Source {
131///     async fn list(&self, cap: u32) -> Result<Vec<String>> {
132///         let repo = &self.repo;
133///         let paged = fetch_capped(FetchStrategy::SingleShot, cap, |_page, limit| async move {
134///             // `repo` 是 `&String`(`Copy`),可在每次调用中重新借出,
135///             // 无需 `.clone()`;此处仅返回不超过 `limit` 条的假数据。
136///             let all: Vec<String> = (0..3).map(|i| format!("{repo}#{i}")).collect();
137///             Ok(all.into_iter().take(limit as usize).collect())
138///         })
139///         .await?;
140///         Ok(paged.items)
141///     }
142/// }
143///
144/// # #[tokio::main]
145/// # async fn main() {
146/// let source = Source { repo: "octocat/hello-world".to_string() };
147/// let items = source.list(10).await.expect("fetch should succeed");
148/// assert_eq!(items.len(), 3);
149/// # }
150/// ```
151pub 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    // Lossless on all supported 32/64-bit platforms: u32::MAX always fits in usize there.
161    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    // Lossless on all supported 32/64-bit platforms: u32::MAX always fits in usize there.
172    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    /// 拆成「纯条目」与「分页元数据」两半。
187    ///
188    /// CLI 层用它把条目放进输出的 `data`(保持数组形状),把元数据放进
189    /// 输出信封的 `pagination` 字段。
190    #[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    /// 记录每次 fetch 调用的 (page, limit),并按预设总量返回数据。
208    #[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        /// 模拟「取第 page 页,每页 limit 条」,数据为 0..total 的连续整数。
223        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        // total=5 < per_page=10 ⇒ 第一页就短,必须停在第 1 页
309        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        // cap=25,per_page=10 ⇒ 需要凑够 26 条:第 1/2 页各 10 条,第 3 页再 10 条 = 30 ≥ 26
318        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        // Discriminates a correct N+1 probe from an N probe. With `want = cap`
327        // (the off-by-one bug), the loop would stop after page 2 holding exactly
328        // 20 items and report truncated = false, even though 30 exist.
329        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        // total=20,per_page=10:第 1、2 页各满 10 条,第 3 页返回 0 条 ⇒ 取尽
342        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}