#![allow(dead_code)]
use std::{
collections::VecDeque,
fmt,
future::{Future, IntoFuture},
ops::Deref,
pin::Pin,
sync::Arc,
task::{Context, Poll},
};
use super::{ApiResponse, Call};
use crate::error::Error;
pub(crate) enum Walk<O> {
Cursor {
get: fn(&O) -> Option<String>,
set: fn(&mut O, String),
before: Option<Cursor<O>>,
},
Page {
first: i64,
get: fn(&O) -> Option<i64>,
set: fn(&mut O, i64),
},
Offset {
get: fn(&O) -> Option<i64>,
set: fn(&mut O, i64),
},
}
pub(crate) struct Cursor<O> {
pub(crate) get: fn(&O) -> Option<String>,
pub(crate) set: fn(&mut O, String),
}
impl<O> Clone for Cursor<O> {
fn clone(&self) -> Self {
*self
}
}
impl<O> Copy for Cursor<O> {}
impl<O> Clone for Walk<O> {
fn clone(&self) -> Self {
*self
}
}
impl<O> Copy for Walk<O> {}
pub(crate) struct Fields<P, T> {
pub(crate) items: fn(&P) -> Option<&Vec<T>>,
pub(crate) items_mut: fn(&mut P) -> Option<&mut Vec<T>>,
pub(crate) next_cursor: Option<fn(&P) -> Option<&str>>,
pub(crate) item_cursor: Option<fn(&T) -> Option<&str>>,
pub(crate) has_more: Option<fn(&P) -> Option<bool>>,
pub(crate) total: Option<fn(&P) -> Option<i64>>,
}
impl<P, T> Clone for Fields<P, T> {
fn clone(&self) -> Self {
*self
}
}
impl<P, T> Copy for Fields<P, T> {}
type PageFuture<P, T> =
Pin<Box<dyn Future<Output = Result<ApiResponse<Page<P, T>>, Error>> + Send>>;
trait Fetch<P, T>: Send + Sync {
fn fetch(&self) -> PageFuture<P, T>;
}
struct PageRequest<O, P, T> {
options: O,
call: Arc<dyn Fn(O) -> Call<P> + Send + Sync>,
walk: Walk<O>,
fields: Fields<P, T>,
}
impl<O: Clone, P, T> Clone for PageRequest<O, P, T> {
fn clone(&self) -> Self {
Self {
options: self.options.clone(),
call: self.call.clone(),
walk: self.walk,
fields: self.fields,
}
}
}
impl<O, P, T> PageRequest<O, P, T>
where
O: Clone + Send + Sync + 'static,
P: Send + Sync + 'static,
T: Send + Sync + 'static,
{
fn after(&self, page: &P) -> Option<Arc<dyn Fetch<P, T>>> {
let fields = self.fields;
let items = (fields.items)(page).map_or(&[][..], Vec::as_slice);
let has_more = fields.has_more.and_then(|has_more| has_more(page));
if items.is_empty() || has_more == Some(false) {
return None;
}
let total = fields.total.and_then(|total| total(page));
let mut options = self.options.clone();
match self.walk {
Walk::Cursor { get, set, before } => {
let backwards = before.filter(|before| (before.get)(&self.options).is_some());
let (get, set) = backwards.map_or((get, set), |before| (before.get, before.set));
let next = match (fields.item_cursor, fields.next_cursor) {
(Some(cursor), _) if backwards.is_some() => items.first().and_then(cursor),
(Some(cursor), _) => items.last().and_then(cursor),
(None, Some(cursor)) => cursor(page),
(None, None) => None,
};
let next = next.filter(|next| {
!next.is_empty() && get(&self.options).as_deref() != Some(*next)
})?;
set(&mut options, next.to_owned());
}
Walk::Page { first, get, set } => {
let current = get(&self.options).unwrap_or(first);
if total.is_some_and(|total| current - first + 1 >= total) {
return None;
}
set(&mut options, current + 1);
}
Walk::Offset { get, set } => {
let count = i64::try_from(items.len()).unwrap_or(i64::MAX);
let offset = get(&self.options).unwrap_or(0).saturating_add(count);
if total.is_some_and(|total| offset >= total) {
return None;
}
set(&mut options, offset);
}
}
Some(Arc::new(Self {
options,
..self.clone()
}))
}
}
impl<O, P, T> Fetch<P, T> for PageRequest<O, P, T>
where
O: Clone + Send + Sync + 'static,
P: Send + Sync + 'static,
T: Send + Sync + 'static,
{
fn fetch(&self) -> PageFuture<P, T> {
let call = (self.call)(self.options.clone());
let request = self.clone();
Box::pin(async move {
let response = call.with_response().await?;
Ok(response.map(|inner| Page {
next: request.after(&inner),
inner,
fields: request.fields,
}))
})
}
}
#[must_use = "a call does nothing until it is awaited"]
pub struct PageCall<P, T> {
first: Arc<dyn Fetch<P, T>>,
}
impl<P, T> PageCall<P, T>
where
P: Send + Sync + 'static,
T: Send + Sync + 'static,
{
pub(crate) fn new<O: Clone + Send + Sync + 'static>(
options: O,
walk: Walk<O>,
fields: Fields<P, T>,
call: impl Fn(O) -> Call<P> + Send + Sync + 'static,
) -> Self {
let first = PageRequest {
options,
call: Arc::new(call),
walk,
fields,
};
Self {
first: Arc::new(first),
}
}
pub async fn with_response(self) -> Result<ApiResponse<Page<P, T>>, Error> {
self.first.fetch().await
}
pub fn items(self) -> Paginator<P, T> {
Paginator {
next: Some(self.first),
pending: None,
buffered: VecDeque::new(),
}
}
pub fn pages(self) -> Pages<P, T> {
Pages(self.items())
}
}
impl<P, T> IntoFuture for PageCall<P, T>
where
P: Send + Sync + 'static,
T: Send + Sync + 'static,
{
type Output = Result<Page<P, T>, Error>;
type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send>>;
fn into_future(self) -> Self::IntoFuture {
let first = self.first.fetch();
Box::pin(async move { first.await.map(ApiResponse::into_data) })
}
}
impl<P, T> fmt::Debug for PageCall<P, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PageCall").finish_non_exhaustive()
}
}
pub struct Page<P, T> {
inner: P,
next: Option<Arc<dyn Fetch<P, T>>>,
fields: Fields<P, T>,
}
impl<P, T> Page<P, T> {
#[must_use]
pub fn items(&self) -> &[T] {
(self.fields.items)(&self.inner).map_or(&[], Vec::as_slice)
}
#[must_use]
pub fn into_items(mut self) -> Vec<T> {
(self.fields.items_mut)(&mut self.inner)
.map(std::mem::take)
.unwrap_or_default()
}
#[must_use]
pub fn into_inner(self) -> P {
self.inner
}
#[must_use]
pub fn has_next_page(&self) -> bool {
self.next.is_some()
}
pub async fn next_page(&self) -> Result<Option<Self>, Error> {
match &self.next {
Some(next) => next
.fetch()
.await
.map(|response| Some(response.into_data())),
None => Ok(None),
}
}
}
impl<P, T> Deref for Page<P, T> {
type Target = P;
fn deref(&self) -> &P {
&self.inner
}
}
impl<P: fmt::Debug, T> fmt::Debug for Page<P, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Page")
.field("inner", &self.inner)
.field("has_next_page", &self.has_next_page())
.finish_non_exhaustive()
}
}
#[must_use = "a paginator does nothing until it is polled"]
pub struct Paginator<P, T> {
next: Option<Arc<dyn Fetch<P, T>>>,
pending: Option<PageFuture<P, T>>,
buffered: VecDeque<T>,
}
impl<P, T> Unpin for Paginator<P, T> {}
impl<P, T> Paginator<P, T>
where
P: Send + Sync + 'static,
T: Send + Sync + 'static,
{
pub async fn next(&mut self) -> Option<Result<T, Error>> {
std::future::poll_fn(|cx| self.poll_item(cx)).await
}
fn poll_item(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<T, Error>>> {
loop {
if let Some(item) = self.buffered.pop_front() {
return Poll::Ready(Some(Ok(item)));
}
match std::task::ready!(self.poll_page(cx)) {
Some(Ok(page)) => self.buffered.extend(page.into_items()),
Some(Err(error)) => return Poll::Ready(Some(Err(error))),
None => return Poll::Ready(None),
}
}
}
fn poll_page(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<Page<P, T>, Error>>> {
if self.pending.is_none() {
let Some(next) = self.next.take() else {
return Poll::Ready(None);
};
self.pending = Some(next.fetch());
}
let response = std::task::ready!(self.pending.as_mut().unwrap().as_mut().poll(cx));
self.pending = None;
let page = response.map(ApiResponse::into_data);
if let Ok(page) = &page {
self.next.clone_from(&page.next);
}
Poll::Ready(Some(page))
}
pub async fn collect(mut self) -> Result<Vec<T>, Error> {
let mut items = Vec::new();
while let Some(item) = self.next().await {
items.push(item?);
}
Ok(items)
}
}
impl<P, T> futures_core::Stream for Paginator<P, T>
where
P: Send + Sync + 'static,
T: Send + Sync + 'static,
{
type Item = Result<T, Error>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.get_mut().poll_item(cx)
}
}
impl<P, T> fmt::Debug for Paginator<P, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Paginator")
.field("buffered", &self.buffered.len())
.finish_non_exhaustive()
}
}
#[must_use = "pages do nothing until polled"]
pub struct Pages<P, T>(Paginator<P, T>);
impl<P, T> Pages<P, T>
where
P: Send + Sync + 'static,
T: Send + Sync + 'static,
{
pub async fn next(&mut self) -> Option<Result<Page<P, T>, Error>> {
std::future::poll_fn(|cx| self.0.poll_page(cx)).await
}
}
impl<P, T> futures_core::Stream for Pages<P, T>
where
P: Send + Sync + 'static,
T: Send + Sync + 'static,
{
type Item = Result<Page<P, T>, Error>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.get_mut().0.poll_page(cx)
}
}
impl<P, T> fmt::Debug for Pages<P, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Pages")
}
}