use crate::EcosystemId;
use crate::error::Result;
use bytes::Bytes;
use std::future::Future;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ListCoverage {
#[default]
Complete,
Truncated,
}
impl ListCoverage {
#[must_use]
pub fn from_link_header(link: Option<&str>) -> Self {
if link.is_some_and(|header| !next_targets(header).is_empty()) {
Self::Truncated
} else {
Self::Complete
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NextPage {
Last,
Next(url::Url),
Rejected,
}
#[must_use]
pub fn next_page(current: &url::Url, link: Option<&str>, trusted: &url::Url) -> NextPage {
let Some(header) = link else {
return NextPage::Last;
};
let targets = next_targets(header);
let Some((first, rest)) = targets.split_first() else {
return NextPage::Last;
};
if first.is_empty() || rest.iter().any(|other| other != first) {
return NextPage::Rejected;
}
match current.join(first) {
Ok(next)
if next.username().is_empty()
&& next.password().is_none()
&& crate::net_policy::is_trusted_prefix(&next, trusted) =>
{
NextPage::Next(next)
}
Ok(_) | Err(_) => NextPage::Rejected,
}
}
fn next_targets(header: &str) -> Vec<&str> {
split_outside_quotes(header, ',')
.filter_map(|link_value| {
let mut parts = split_outside_quotes(link_value, ';');
let target = parts.next()?;
parts.any(is_next_rel).then(|| {
target
.trim()
.strip_circumfix('<', '>')
.map_or("", str::trim)
})
})
.collect()
}
fn is_next_rel(param: &str) -> bool {
let Some((name, value)) = param.split_once('=') else {
return false;
};
name.trim().eq_ignore_ascii_case("rel")
&& value
.trim()
.trim_matches('"')
.split_ascii_whitespace()
.any(|token| token.eq_ignore_ascii_case("next"))
}
fn split_outside_quotes(input: &str, separator: char) -> impl Iterator<Item = &str> {
let mut in_quotes = false;
let mut in_target = false;
let mut start = 0;
let mut pieces = Vec::new();
let mut escaped = false;
for (idx, ch) in input.char_indices() {
if std::mem::take(&mut escaped) {
continue;
}
match ch {
'\\' if in_quotes => escaped = true,
'"' if !in_target => in_quotes = !in_quotes,
'<' if !in_quotes => in_target = true,
'>' if !in_quotes => in_target = false,
c if c == separator && !in_quotes && !in_target => {
pieces.extend(input.get(start..idx));
start = idx + c.len_utf8();
}
_ => {}
}
}
pieces.extend(input.get(start..));
pieces.into_iter()
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Paginated<T> {
pub items: Vec<T>,
pub coverage: ListCoverage,
}
impl<T> Paginated<T> {
#[must_use]
pub const fn new(items: Vec<T>, coverage: ListCoverage) -> Self {
Self { items, coverage }
}
}
const CONCURRENCY: usize = 5;
#[must_use]
pub const fn page_has_more(page_len: usize) -> bool {
page_len >= 100
}
pub fn warn_if_pagination_truncated(
provider: &str,
ecosystem: EcosystemId,
noun: &str,
name: &str,
page: u32,
page_len: usize,
max_pages: u32,
) {
if page == max_pages && page_has_more(page_len) {
let name = crate::redact::redact_declaration_key(name);
tracing::warn!(
package = %name,
pages_fetched = max_pages,
%ecosystem,
"{ecosystem} {noun} pagination for '{name}' stopped at the {max_pages}-page cap \
while {provider} reported more pages available; the fetched version list may be \
truncated"
);
}
}
pub async fn paginate_pages<T, F, Fut, P>(
provider: &str,
ecosystem: EcosystemId,
noun: &str,
name: &str,
max_pages: u32,
mut fetch_page: F,
mut parse_page: P,
) -> Result<Paginated<T>>
where
F: FnMut(u32) -> Fut,
Fut: Future<Output = Result<Bytes>>,
P: FnMut(&Bytes) -> Result<Vec<T>>,
{
use futures::stream::{self, StreamExt};
let mut items = Vec::new();
let first_page = fetch_page(1).await?;
let first_items = parse_page(&first_page)?;
let first_page_len = first_items.len();
items.extend(first_items);
if !page_has_more(first_page_len) {
return Ok(Paginated {
items,
coverage: ListCoverage::Complete,
});
}
let mut coverage = ListCoverage::Truncated;
let mut page = 2u32;
#[expect(
clippy::cast_possible_truncation,
reason = "CONCURRENCY is a small hardcoded constant (5), never close to u32::MAX"
)]
'batches: while page <= max_pages {
let batch_end = (page + CONCURRENCY as u32 - 1).min(max_pages);
let mut stream = stream::iter(page..=batch_end)
.map(&mut fetch_page)
.buffered(CONCURRENCY);
let mut current_page = page;
while let Some(data) = stream.next().await {
let page_items = parse_page(&data?)?;
let page_len = page_items.len();
items.extend(page_items);
if !page_has_more(page_len) {
coverage = ListCoverage::Complete;
break 'batches;
}
warn_if_pagination_truncated(
provider,
ecosystem,
noun,
name,
current_page,
page_len,
max_pages,
);
current_page += 1;
}
page = batch_end + 1;
}
Ok(Paginated { items, coverage })
}
#[cfg(test)]
#[expect(
clippy::cast_possible_truncation,
reason = "#673: fixed test-fixture lengths cast to u32 never approach truncation range"
)]
mod tests {
use super::*;
#[cfg(feature = "test-util")]
use crate::test_util::capture_tracing_output_async;
#[test]
fn from_link_header_grammar() {
let truncated = [
r#"<https://r/p?page=2>; rel="next""#,
"<https://r/p?page=2>; rel=next",
r#"<https://r/p?page=2>; rel="Next""#,
r#"<https://r/p?page=2>; REL="NEXT""#,
r#"<https://r/p?page=2>; rel="last next""#,
r#"<https://r/p>; rel="latest-version", <https://r/p?page=2>; rel="next""#,
r#"<https://r/p?a=1,2>; title="x, y"; rel="next""#,
r#"<https://r/p>; title="a\", <https://r/q>; rel=\"x"; rel="next""#,
r#"<https://r/p>; title="a \" b"; rel="next""#,
];
for header in truncated {
assert_eq!(
ListCoverage::from_link_header(Some(header)),
ListCoverage::Truncated,
"{header}"
);
}
let complete = [
r#"<https://r/p>; rel="latest-version""#,
r#"<https://r/p>; rel="canonical""#,
r#"<https://r/next>; rel="nextish""#,
r#"<https://r/p>; title="x \"; rel=next\" y""#,
r#"<https://r/p?rel=next>; title="rel=next""#,
"",
];
for header in complete {
assert_eq!(
ListCoverage::from_link_header(Some(header)),
ListCoverage::Complete,
"{header}"
);
}
assert_eq!(ListCoverage::from_link_header(None), ListCoverage::Complete);
}
fn next(current: &str, link: Option<&str>, trusted: &str) -> NextPage {
next_page(
&url::Url::parse(current).unwrap(),
link,
&url::Url::parse(trusted).unwrap(),
)
}
#[test]
fn next_page_follows_one_trusted_target_and_rejects_the_rest() {
let current = "https://r.example/api/acme/net";
let trusted = "https://r.example/api/";
let url = |s: &str| NextPage::Next(url::Url::parse(s).unwrap());
assert_eq!(next(current, None, trusted), NextPage::Last);
assert_eq!(
next(
current,
Some(r#"<https://r.example/api/acme/net>; rel="canonical""#),
trusted
),
NextPage::Last
);
assert_eq!(
next(current, Some(r#"<?page=2>; rel="next""#), trusted),
url("https://r.example/api/acme/net?page=2")
);
assert_eq!(
next(
current,
Some(
r#"<https://r.example/api/acme/net?page=2>; rel=next, <https://r.example/api/acme/net?page=2>; rel="next""#
),
trusted
),
url("https://r.example/api/acme/net?page=2")
);
let rejected = [
r#"<https://r.example/api/acme/net?page=2>; rel="next", <https://r.example/api/acme/net?page=3>; rel="next""#,
r#"<>; rel="next""#,
r#"https://r.example/api/acme/net?page=2; rel="next""#,
r#"<https://evil.example/api/acme/net?page=2>; rel="next""#,
r#"<https://r.example/other/acme/net?page=2>; rel="next""#,
r#"<http://r.example/api/acme/net?page=2>; rel="next""#,
r#"<https://user:pw@r.example/api/acme/net?page=2>; rel="next""#,
r#"<https://r.example/apiEVIL/acme/net>; rel="next""#,
];
for header in rejected {
assert_eq!(
next(current, Some(header), trusted),
NextPage::Rejected,
"{header}"
);
}
}
#[test]
fn test_page_has_more_full_page_continues() {
assert!(page_has_more(100));
}
#[test]
fn test_page_has_more_partial_page_stops() {
assert!(!page_has_more(99));
assert!(!page_has_more(0));
}
#[cfg(feature = "test-util")]
#[tokio::test]
async fn test_warn_if_pagination_truncated_uses_passed_max_pages_not_a_constant() {
let output = capture_tracing_output_async(async {
warn_if_pagination_truncated(
"GitLab",
EcosystemId::GitlabCi,
"tags",
"org/repo",
3,
100,
3,
);
})
.await;
assert!(output.contains("org/repo"), "output was: {output}");
assert!(output.contains("GitLab"), "output was: {output}");
assert!(output.contains('3'), "output was: {output}");
let silent = capture_tracing_output_async(async {
warn_if_pagination_truncated(
"GitLab",
EcosystemId::GitlabCi,
"tags",
"org/repo",
2,
100,
3,
);
})
.await;
assert!(
silent.is_empty(),
"must not warn below the passed cap: {silent}"
);
}
fn page_json(count: usize) -> Bytes {
let entries: Vec<String> = (0..count).map(|i| format!(r#"{{"n":{i}}}"#)).collect();
Bytes::from(format!("[{}]", entries.join(",")))
}
fn parse_page(data: &Bytes) -> Result<Vec<u32>> {
let value: serde_json::Value = crate::parser::parse_json_checked(data)?;
Ok(value
.as_array()
.map(|arr| (0..arr.len() as u32).collect())
.unwrap_or_default())
}
#[tokio::test]
async fn test_paginate_pages_single_page_fetches_exactly_once() {
use std::sync::atomic::{AtomicU32, Ordering};
let calls = AtomicU32::new(0);
let result = paginate_pages(
"GitLab",
EcosystemId::GitlabCi,
"tags",
"org/repo",
30,
|page| {
calls.fetch_add(1, Ordering::SeqCst);
async move {
match page {
1 => Ok(page_json(42)),
_ => panic!("page {page} must not be fetched"),
}
}
},
parse_page,
)
.await
.unwrap();
assert_eq!(calls.load(Ordering::SeqCst), 1);
assert_eq!(result.items.len(), 42);
}
#[tokio::test]
async fn test_paginate_pages_stops_after_partial_page_at_custom_cap() {
let result = paginate_pages(
"GitLab",
EcosystemId::GitlabCi,
"tags",
"org/repo",
5,
|page| async move {
match page {
1 => Ok(page_json(100)),
2..=5 => Ok(page_json(10)),
_ => panic!("page {page} must not be fetched beyond the 5-page cap"),
}
},
parse_page,
)
.await
.unwrap();
assert_eq!(result.items.len(), 110);
assert_eq!(result.coverage, ListCoverage::Complete);
}
#[tokio::test]
async fn test_paginate_pages_single_partial_page_is_complete() {
let result = paginate_pages(
"GitLab",
EcosystemId::GitlabCi,
"tags",
"org/repo",
5,
|_page| async move { Ok(page_json(3)) },
parse_page,
)
.await
.unwrap();
assert_eq!(result.coverage, ListCoverage::Complete);
}
#[tokio::test]
async fn test_paginate_pages_cap_reached_with_full_last_page_is_truncated() {
let result = paginate_pages(
"GitLab",
EcosystemId::GitlabCi,
"tags",
"org/repo",
3,
|_page| async move { Ok(page_json(100)) },
parse_page,
)
.await
.unwrap();
assert_eq!(result.items.len(), 300);
assert_eq!(result.coverage, ListCoverage::Truncated);
}
#[tokio::test]
async fn test_paginate_pages_partial_page_exactly_at_cap_is_complete() {
let result = paginate_pages(
"GitLab",
EcosystemId::GitlabCi,
"tags",
"org/repo",
3,
|page| async move {
match page {
1 | 2 => Ok(page_json(100)),
3 => Ok(page_json(7)),
_ => panic!("page {page} must not be fetched beyond the 3-page cap"),
}
},
parse_page,
)
.await
.unwrap();
assert_eq!(result.items.len(), 207);
assert_eq!(result.coverage, ListCoverage::Complete);
}
#[test]
fn test_list_coverage_default_is_complete() {
assert_eq!(ListCoverage::default(), ListCoverage::Complete);
}
}