wellfriend-document-sdk 1.0.0

Official async Rust SDK for the Wellfriend document API: typed document tools, pipelines, streaming uploads and downloads, retries and webhook verification.
Documentation
use std::future::Future;
use std::pin::Pin;

use futures_util::{stream, Stream, StreamExt, TryStreamExt};
use serde::{Deserialize, Serialize};

use crate::error::Result;
use crate::Object;

/// One page of a list.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(
    rename_all = "camelCase",
    bound(serialize = "T: Serialize", deserialize = "T: Deserialize<'de>")
)]
pub struct Page<T> {
    /// The items on this page.
    #[serde(default = "Vec::new", deserialize_with = "crate::util::null_default")]
    pub items: Vec<T>,
    /// The cursor for the next page; `None` on the last page.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<String>,
    /// Fields this SDK version does not model.
    #[serde(flatten)]
    pub extra: Object,
}

impl<T> Default for Page<T> {
    fn default() -> Self {
        Page {
            items: Vec::new(),
            next_cursor: None,
            extra: Object::new(),
        }
    }
}

impl<T> Page<T> {
    /// Whether another page follows.
    pub fn has_more(&self) -> bool {
        self.next_cursor
            .as_deref()
            .is_some_and(|cursor| !cursor.is_empty())
    }
}

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()
    }
}

/// Every item of a list, fetching the following pages as you consume it.
///
/// ```no_run
/// # async fn run(wf: wellfriend::Wellfriend) -> wellfriend::Result<()> {
/// use futures_util::TryStreamExt;
///
/// let mut documents = wf.documents().stream(None);
/// while let Some(document) = documents.try_next().await? {
///     println!("{} {}", document.id, document.title);
/// }
/// # Ok(())
/// # }
/// ```
pub type PageStream<T> = Pin<Box<dyn Stream<Item = Result<T>> + Send + 'static>>;

pub(crate) type PageFuture<T> = Pin<Box<dyn Future<Output = Result<Page<T>>> + Send + 'static>>;

/// Pages through a list: `fetch` gets the cursor of the page to load (`None` for the first).
pub(crate) fn paginate<T, F>(fetch: F) -> PageStream<T>
where
    T: Send + 'static,
    F: FnMut(Option<String>) -> PageFuture<T> + Send + 'static,
{
    enum State<F> {
        Next(F, Option<String>),
        Done,
    }
    let pages = stream::try_unfold(State::Next(fetch, None), |state| async move {
        match state {
            State::Done => Ok::<_, crate::Error>(None),
            State::Next(mut fetch, cursor) => {
                let page = fetch(cursor).await?;
                let next = if page.has_more() {
                    State::Next(fetch, page.next_cursor.clone())
                } else {
                    State::Done
                };
                Ok(Some((page.items, next)))
            }
        }
    });
    Box::pin(
        pages
            .map_ok(|items| stream::iter(items.into_iter().map(Ok)))
            .try_flatten()
            .boxed(),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures_util::TryStreamExt;

    #[tokio::test]
    async fn follows_cursors_until_the_last_page() {
        let stream = paginate(|cursor: Option<String>| -> PageFuture<u32> {
            Box::pin(async move {
                Ok(match cursor.as_deref() {
                    None => Page {
                        items: vec![1, 2],
                        next_cursor: Some("b".into()),
                        extra: Object::new(),
                    },
                    Some("b") => Page {
                        items: vec![3],
                        next_cursor: Some(String::new()),
                        extra: Object::new(),
                    },
                    Some(other) => panic!("unexpected cursor {other}"),
                })
            })
        });
        let all: Vec<u32> = stream.try_collect().await.unwrap();
        assert_eq!(all, vec![1, 2, 3]);
    }
}