moonproof-indexer-client 0.2.2

Rust client for the Midnight indexer's GraphQL API
Documentation
//! Generic page-draining helpers for indexer queries that take
//! limit/offset.
//!
//! Most indexer queries (e.g. `spo_list`, `transactions`) expose raw
//! limit/offset params at the [`crate::PublicDataProvider`] surface.
//! Callers that want every record across all pages would otherwise
//! write the same loop everywhere — this module factors it out.
//!
//! The helpers accept a fetcher closure that takes a `(limit,
//! offset)` window and returns one page's worth of items. The
//! returned [`Stream`] yields items one by one, fetching the next
//! page lazily as the consumer drains the current one. A short page
//! (smaller than `page_size`) signals end-of-stream.
//!
//! ## Example
//!
//! ```ignore
//! use moonproof_indexer_client::pagination::paginate;
//! use futures::StreamExt;
//!
//! let stream = paginate(500, |limit, offset| async move {
//!     provider.spo_list(Some(limit), Some(offset), None).await
//! });
//! tokio::pin!(stream);
//! while let Some(item) = stream.next().await {
//!     let spo = item?;
//!     // ...
//! }
//! ```

use std::future::Future;

use futures_util::stream::Stream;

use crate::error::IndexerError;

/// Drain a paginated indexer query into a [`Stream`] of items.
///
/// `page_size` is the per-request batch (also the limit passed to the
/// fetcher). `fetch` runs once per page and is awaited inline — the
/// returned stream will not start fetching the next page until the
/// previous page's items have been consumed.
///
/// Errors from `fetch` are surfaced one-shot through the stream:
/// after an error the stream ends.
pub fn paginate<T, Fut, F>(
    page_size: i64,
    mut fetch: F,
) -> impl Stream<Item = Result<T, IndexerError>>
where
    T: 'static,
    F: FnMut(i64, i64) -> Fut + 'static,
    Fut: Future<Output = Result<Vec<T>, IndexerError>> + 'static,
{
    async_stream::try_stream! {
        let mut offset: i64 = 0;
        loop {
            let page = fetch(page_size, offset).await?;
            let len = page.len();
            for item in page {
                yield item;
            }
            // Short page → no more data.
            if i64::try_from(len).is_ok_and(|len| len < page_size) {
                break;
            }
            offset += page_size;
            // Safety: a real indexer returning more than i64::MAX
            // records is impossible. Bail before overflow rather than
            // wrap silently.
            if offset < 0 {
                break;
            }
        }
    }
}

/// Drain a paginated query into a `Vec<T>`. Convenience for callers
/// that prefer materialising all pages at once over consuming a
/// stream. Same semantics as [`paginate`] otherwise.
pub async fn collect_all<T, Fut, F>(page_size: i64, fetch: F) -> Result<Vec<T>, IndexerError>
where
    T: 'static,
    F: FnMut(i64, i64) -> Fut + 'static,
    Fut: Future<Output = Result<Vec<T>, IndexerError>> + 'static,
{
    use futures_util::StreamExt;
    let mut out = Vec::new();
    let stream = paginate(page_size, fetch);
    futures_util::pin_mut!(stream);
    while let Some(item) = stream.next().await {
        out.push(item?);
    }
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures_util::StreamExt;
    use std::cell::RefCell;
    use std::rc::Rc;

    #[tokio::test(flavor = "current_thread")]
    async fn collect_all_drains_every_page() {
        let total = 1234;
        let calls = Rc::new(RefCell::new(0));
        let calls_clone = calls.clone();
        let out: Vec<i64> = collect_all(100, move |limit, offset| {
            *calls_clone.borrow_mut() += 1;
            async move {
                let end = (offset + limit).min(total);
                Ok((offset..end).collect())
            }
        })
        .await
        .unwrap();
        assert_eq!(out.len(), usize::try_from(total).unwrap());
        assert_eq!(out.first().copied(), Some(0));
        assert_eq!(out.last().copied(), Some(total - 1));
        // 1234 / 100 = 13 full + 1 short = 13 calls (last short page
        // ends the loop without an extra request).
        let n_calls = *calls.borrow();
        assert!(
            (13..=14).contains(&n_calls),
            "expected ~13 page fetches, got {n_calls}",
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn paginate_stops_on_short_page() {
        let stream = paginate(50, |_limit, offset| async move {
            if offset > 0 {
                Ok(Vec::<i64>::new())
            } else {
                // Exactly 10 items — shorter than page_size, so the
                // stream stops without fetching more.
                Ok((0..10).collect())
            }
        });
        futures_util::pin_mut!(stream);
        let mut count = 0;
        while let Some(item) = stream.next().await {
            item.unwrap();
            count += 1;
        }
        assert_eq!(count, 10);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn paginate_propagates_errors() {
        let stream = paginate::<i64, _, _>(10, |_limit, _offset| async move {
            Err(IndexerError::GraphQl("boom".into()))
        });
        futures_util::pin_mut!(stream);
        let first: Result<i64, IndexerError> = stream.next().await.expect("at least one item");
        assert!(first.is_err());
        // After an error the stream ends.
        let next: Option<Result<i64, IndexerError>> = stream.next().await;
        assert!(next.is_none());
    }
}