use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use futures_core::Stream;
use super::error::Result;
use super::query::Query;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Page<T> {
pub items: Vec<T>,
pub total_count: Option<usize>,
pub result_count: Option<usize>,
pub next_link: Option<String>,
pub partial: bool,
pub offset: usize,
}
impl<T> Page<T> {
#[must_use]
pub fn new(items: Vec<T>) -> Self {
Self {
result_count: Some(items.len()),
items,
total_count: None,
next_link: None,
partial: false,
offset: 0,
}
}
#[must_use]
pub fn with_partial(mut self, partial: bool) -> Self {
self.partial = partial;
self
}
#[must_use]
pub fn with_total_count(mut self, total: usize) -> Self {
self.total_count = Some(total);
self
}
#[must_use]
pub fn with_next_link(mut self, link: impl Into<String>) -> Self {
self.next_link = Some(link.into());
self
}
#[must_use]
pub fn with_offset(mut self, offset: usize) -> Self {
self.offset = offset;
self
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
#[must_use]
pub fn len(&self) -> usize {
self.items.len()
}
#[must_use]
pub fn next_offset(&self) -> usize {
self.offset + self.items.len()
}
#[must_use]
pub fn has_more(&self, page_size: usize) -> bool {
if self.items.is_empty() {
return false;
}
if let Some(total) = self.total_count {
return self.next_offset() < total;
}
if self.partial || self.next_link.is_some() {
return true;
}
self.items.len() >= page_size
}
}
impl<T> IntoIterator for Page<T> {
type Item = T;
type IntoIter = std::vec::IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
self.items.into_iter()
}
}
#[must_use]
pub fn next_link(header: &str) -> Option<String> {
let bytes = header.as_bytes();
let mut at = 0;
while at < bytes.len() {
let open = at + bytes[at..].iter().position(|b| *b == b'<')?;
let close = open + 1 + bytes[open + 1..].iter().position(|b| *b == b'>')?;
let url = &header[open + 1..close];
let (params, next) = split_link_value(header, close + 1);
if !url.is_empty() && params_name_the_next_relation(params) {
return Some(url.to_owned());
}
at = next;
}
None
}
fn split_link_value(header: &str, from: usize) -> (&str, usize) {
let bytes = header.as_bytes();
let mut quoted = false;
let mut at = from;
while at < bytes.len() {
match bytes[at] {
b'\\' if quoted => at += 1,
b'"' => quoted = !quoted,
b',' if !quoted => return (&header[from..at], at + 1),
_ => {}
}
at += 1;
}
(&header[from..], bytes.len())
}
fn params_name_the_next_relation(params: &str) -> bool {
split_parameters(params).any(|param| {
let Some((name, value)) = param.split_once('=') else {
return false;
};
name.trim().eq_ignore_ascii_case("rel")
&& value
.trim()
.trim_matches('"')
.split_whitespace()
.any(|relation| relation.eq_ignore_ascii_case("next"))
})
}
fn split_parameters(params: &str) -> impl Iterator<Item = &str> {
let mut quoted = false;
let mut start = 0;
let mut out = Vec::new();
for (at, byte) in params.bytes().enumerate() {
match byte {
b'"' => quoted = !quoted,
b';' if !quoted => {
out.push(¶ms[start..at]);
start = at + 1;
}
_ => {}
}
}
out.push(¶ms[start..]);
out.into_iter().map(str::trim).filter(|p| !p.is_empty())
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum PageRequest {
Query(Query),
Follow(String),
}
pub fn paginate<T, F, Fut>(query: Query, fetch: F) -> PageStream<T>
where
F: Fn(PageRequest) -> Fut + Send + 'static,
Fut: Future<Output = Result<Page<T>>> + Send + 'static,
T: Send + 'static,
{
let page_size = query.limit_value().unwrap_or(DEFAULT_PAGE_SIZE);
let start = query.offset_value().unwrap_or(0);
PageStream {
state: State::Idle(Next::Offset(start)),
buffer: Vec::new().into_iter(),
page_size,
query,
fetch: Box::new(move |request| Box::pin(fetch(request))),
visited: std::collections::HashSet::new(),
following: false,
done: false,
}
}
pub const DEFAULT_PAGE_SIZE: usize = 20;
type BoxFuture<T> = Pin<Box<dyn Future<Output = Result<Page<T>>> + Send>>;
type FetchFn<T> = Box<dyn Fn(PageRequest) -> BoxFuture<T> + Send>;
enum Next {
Offset(usize),
Link(String),
}
enum State<T> {
Idle(Next),
Fetching(BoxFuture<T>),
}
pub struct PageStream<T> {
state: State<T>,
buffer: std::vec::IntoIter<T>,
page_size: usize,
query: Query,
fetch: FetchFn<T>,
visited: std::collections::HashSet<String>,
following: bool,
done: bool,
}
impl<T> std::fmt::Debug for PageStream<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PageStream")
.field("page_size", &self.page_size)
.field("done", &self.done)
.finish_non_exhaustive()
}
}
impl<T: Unpin> Stream for PageStream<T> {
type Item = Result<T>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
loop {
if let Some(item) = this.buffer.next() {
return Poll::Ready(Some(Ok(item)));
}
if this.done {
return Poll::Ready(None);
}
match &mut this.state {
State::Idle(Next::Offset(offset)) => {
let query = this.query.clone().offset(*offset).limit(this.page_size);
this.state = State::Fetching((this.fetch)(PageRequest::Query(query)));
}
State::Idle(Next::Link(url)) => {
let url = url.clone();
this.state = State::Fetching((this.fetch)(PageRequest::Follow(url)));
}
State::Fetching(future) => match future.as_mut().poll(cx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Err(error)) => {
this.done = true;
return Poll::Ready(Some(Err(error)));
}
Poll::Ready(Ok(page)) => {
this.state = State::Idle(match &page.next_link {
Some(_) if page.items.is_empty() => {
this.done = true;
Next::Offset(page.next_offset())
}
Some(url) if !this.visited.contains(url) => {
this.visited.insert(url.clone());
Next::Link(url.clone())
}
Some(_) => {
this.done = true;
Next::Offset(page.next_offset())
}
None if this.following => {
this.done = true;
Next::Offset(page.next_offset())
}
None => {
if !page.has_more(this.page_size) {
this.done = true;
}
Next::Offset(page.next_offset())
}
});
this.following = matches!(this.state, State::Idle(Next::Link(_)));
this.buffer = page.items.into_iter();
}
},
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn page(items: Vec<u8>, total: Option<usize>, offset: usize) -> Page<u8> {
let page = Page::new(items).with_offset(offset);
match total {
Some(total) => page.with_total_count(total),
None => page,
}
}
#[test]
fn has_more_prefers_the_total_count_header() {
assert!(page(vec![1, 2], Some(5), 0).has_more(2));
assert!(!page(vec![1, 2], Some(2), 0).has_more(2));
}
#[test]
fn has_more_uses_a_next_link_when_there_is_no_total() {
let mut short = page(vec![1], None, 0);
assert!(!short.has_more(2), "no link, short page: done");
short.next_link = Some("https://host/productOffering?offset=1".into());
assert!(short.has_more(2), "the server said there is a next page");
}
#[test]
fn a_206_says_there_is_more_when_no_count_does() {
let capped = page(vec![1, 2], None, 0).with_partial(true);
assert!(
capped.has_more(50),
"a short page marked 206 is not the end of the collection"
);
assert!(!page(vec![1, 2], None, 0).has_more(50));
let mut counted = page(vec![1, 2], Some(2), 0);
counted.partial = true;
assert!(
!counted.has_more(50),
"the count is exact; the status is not"
);
}
#[test]
fn has_more_falls_back_to_a_full_page() {
assert!(page(vec![1, 2], None, 0).has_more(2));
assert!(!page(vec![1], None, 0).has_more(2));
assert!(!page(vec![], None, 0).has_more(2));
}
#[tokio::test]
async fn a_link_after_an_empty_page_does_not_stream_forever() {
use futures::StreamExt as _;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
let calls = Arc::new(AtomicUsize::new(0));
let seen = calls.clone();
let mut stream = paginate(Query::new().limit(2), move |_| {
let calls = seen.clone();
async move {
let n = calls.fetch_add(1, Ordering::SeqCst);
Ok(if n == 0 {
Page::new(vec![1u8, 2]).with_next_link("https://host/a?cursor=1")
} else {
Page::new(Vec::new()).with_next_link(format!("https://host/a?cursor={}", n + 1))
})
}
});
let items: Vec<u8> = (&mut stream)
.map(|item| item.expect("no error"))
.collect()
.await;
assert_eq!(items, [1, 2]);
assert_eq!(
calls.load(Ordering::SeqCst),
2,
"the empty page ended it; anything more is an unbounded poll"
);
}
#[test]
fn an_empty_page_ends_the_sequence_whatever_the_headers_say() {
let mut empty = page(vec![], Some(1000), 0);
empty.next_link = Some("https://host/next".into());
assert!(!empty.has_more(20));
}
#[test]
fn next_offset_advances_by_page_length() {
assert_eq!(page(vec![1, 2, 3], None, 10).next_offset(), 13);
}
#[test]
fn parses_the_next_relation_from_a_link_header() {
let header =
r#"<https://host/a?offset=0>; rel="prev", <https://host/a?offset=40>; rel="next""#;
assert_eq!(
next_link(header).as_deref(),
Some("https://host/a?offset=40")
);
assert_eq!(next_link(r#"<https://host/a>; rel="prev""#), None);
assert_eq!(next_link("nonsense"), None);
}
#[test]
fn link_relation_matching_is_case_insensitive_and_quote_tolerant() {
assert!(next_link("<https://host/a>; REL=next").is_some());
}
#[test]
fn a_comma_inside_the_url_does_not_end_the_link() {
let header = r#"<https://host/productOffering?state=held,pending&offset=40>; rel="next""#;
assert_eq!(
next_link(header).as_deref(),
Some("https://host/productOffering?state=held,pending&offset=40")
);
}
#[test]
fn a_semicolon_inside_the_url_is_not_a_parameter_separator() {
let header = r#"<https://host/a?cursor=x;y>; rel="next""#;
assert_eq!(
next_link(header).as_deref(),
Some("https://host/a?cursor=x;y")
);
}
#[test]
fn rel_may_name_several_relation_types() {
assert_eq!(
next_link(r#"<https://host/a?offset=40>; rel="next last""#).as_deref(),
Some("https://host/a?offset=40")
);
assert_eq!(
next_link(r#"<https://host/a>; rel="prev first""#),
None,
"a list that does not contain `next` is not a next link"
);
}
#[test]
fn a_comma_inside_a_quoted_parameter_does_not_end_the_link() {
let header =
r#"<https://host/a>; title="one, two"; rel="prev", <https://host/b>; rel="next""#;
assert_eq!(next_link(header).as_deref(), Some("https://host/b"));
}
#[test]
fn the_next_relation_is_found_among_several_links() {
let header = concat!(
r#"<https://host/a?offset=0>; rel="first", "#,
r#"<https://host/a?offset=20>; rel="prev", "#,
r#"<https://host/a?offset=60>; rel="next", "#,
r#"<https://host/a?offset=99>; rel="last""#,
);
assert_eq!(
next_link(header).as_deref(),
Some("https://host/a?offset=60")
);
}
#[test]
fn a_malformed_header_yields_no_link_rather_than_panicking() {
for header in [
"",
"nonsense",
"<unterminated; rel=\"next\"",
"<>; rel=\"next\"",
">;<",
"<a>; rel=\"next",
] {
let _ = next_link(header);
}
assert_eq!(
next_link("<>; rel=\"next\""),
None,
"a link naming nowhere is no link: following it would fail as a \
cross-origin refusal rather than ending the collection"
);
}
}