ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
Documentation
//! The size-or-time batch: items go in one at a time and come out in one piece.

use core::{num::NonZeroUsize, time::Duration};
use std::time::Instant;

#[cfg(test)]
mod tests;

/// What a [`Batcher::push`] did with the item.
///
/// Three answers rather than two, and the third is what makes `max_items` a BOUND instead of a
/// convention. [`Full`](Self::Full) says *the item is in and the batch is now at its limit*;
/// [`Refused`](Self::Refused) says *the batch was already at its limit, so here is your item back*.
/// A driver that flushes the moment it sees `Full` never sees `Refused` — but one that flushes only
/// on the timer, using the count purely as a ceiling, is a perfectly ordinary driver, and it is the
/// one for whose sake the item is handed back rather than dropped or appended past the ceiling.
#[derive(Debug, PartialEq, Eq)]
#[must_use = "a dropped answer can leave a full batch unflushed, or lose the item it handed back"]
pub enum Push<T> {
  /// The item joined the open batch and room remains.
  Queued,
  /// The item joined and the batch now holds `max_items` — drain it.
  Full,
  /// The batch was ALREADY at `max_items`: nothing was queued and the item comes back untouched.
  ///
  /// Drain, then offer it again — the second offer cannot be refused, because a drained batch is
  /// empty and `max_items` is non-zero.
  Refused(T),
}

/// A batch that closes on whichever comes first: `max_items` items, or `max_wait` since it opened.
///
/// The wait is measured from the batch's OPENING — the instant its first item arrived — and not
/// from the last one, so a steady trickle still lands on a fixed cadence instead of being pushed
/// out of reach by its own arrivals. Draining resets both halves: the next push opens a new batch
/// with a new clock.
///
/// See the [module note](super) for the loop that drives this and for why nothing here reads a
/// clock.
#[derive(Debug)]
pub struct Batcher<T> {
  max_items: NonZeroUsize,
  max_wait: Duration,
  // `Some` exactly while `items` is non-empty — the instant the OPEN batch took its first item.
  // Set by the push that finds the batch empty and cleared by the drain that empties it, which is
  // the pair that makes "push after drain reopens with a fresh clock" a property of the type rather
  // than of the caller's order of operations.
  opened_at: Option<Instant>,
  items: Vec<T>,
}

impl<T> Batcher<T> {
  /// A batcher that closes at `max_items` items or `max_wait` after the batch opened.
  ///
  /// `NonZeroUsize` rather than `usize` because a zero ceiling has no coherent reading: a batch that
  /// may hold no items is full before it opens, and every push would be refused forever. The refusal
  /// is therefore spent at the type and never at run time.
  #[must_use]
  pub const fn new(max_items: NonZeroUsize, max_wait: Duration) -> Self {
    Self {
      max_items,
      max_wait,
      opened_at: None,
      items: Vec::new(),
    }
  }

  /// The count that both triggers a flush and bounds the batch.
  #[must_use]
  pub const fn max_items(&self) -> NonZeroUsize {
    self.max_items
  }

  /// How long an open batch may stay open, measured from the arrival of its first item.
  #[must_use]
  pub const fn max_wait(&self) -> Duration {
    self.max_wait
  }

  /// How many items the open batch holds — never more than [`max_items`](Self::max_items).
  #[must_use]
  pub fn len(&self) -> usize {
    self.items.len()
  }

  /// Whether no batch is open.
  #[must_use]
  pub fn is_empty(&self) -> bool {
    self.items.is_empty()
  }

  /// Offer `item` to the open batch, opening one at `now` if none is open.
  ///
  /// `now` is spent only on the push that OPENS a batch; a push into an open one ignores it, because
  /// the wait is the batch's and not the item's.
  pub fn push(&mut self, item: T, now: Instant) -> Push<T> {
    if self.items.len() >= self.max_items.get() {
      return Push::Refused(item);
    }
    if self.items.is_empty() {
      self.opened_at = Some(now);
    }
    self.items.push(item);
    if self.items.len() >= self.max_items.get() {
      Push::Full
    } else {
      Push::Queued
    }
  }

  /// When the open batch must flush — its opening plus [`max_wait`](Self::max_wait), or `None` where
  /// no batch is open.
  ///
  /// This is the instant a driving loop parks until. `None` is the answer that says *park on
  /// arrivals alone*: an empty batcher has no deadline, because there is nothing waiting to be late.
  ///
  /// An unrepresentable sum — an absurd `max_wait` against an `Instant` near its platform ceiling —
  /// reads as the opening itself, so the batch flushes at once. Degrading to *no batching* keeps the
  /// items moving; degrading to `None` would strand them behind a timer that never fires.
  #[must_use]
  pub fn deadline(&self) -> Option<Instant> {
    self
      .opened_at
      .map(|opened_at| opened_at.checked_add(self.max_wait).unwrap_or(opened_at))
  }

  /// Whether the open batch is due at `now` — full, or past its deadline.
  ///
  /// An empty batcher is never ready. Note that this asks about the TIMER and the COUNT only: an END
  /// punctuation beats both and is spent through [`drain`](Self::drain) directly.
  #[must_use]
  pub fn ready(&self, now: Instant) -> bool {
    self.items.len() >= self.max_items.get()
      || self.deadline().is_some_and(|deadline| now >= deadline)
  }

  /// Take the open batch and reset — whatever is there, whether or not it is due.
  ///
  /// The unconditional door, and therefore the PUNCTUATION door as well: a driver that has seen an
  /// END calls this without consulting [`ready`](Self::ready), which is what *punctuation beats the
  /// timer* means in a machine that has no timer. An empty batcher drains to an empty vector rather
  /// than refusing, so the END path is one line either way.
  ///
  /// The batch's allocation goes WITH the batch. The next push opens a new one, which is the right
  /// ownership for a value the caller is about to send somewhere.
  #[must_use = "the drained batch is the only copy — dropping it drops the items"]
  pub fn drain(&mut self) -> Vec<T> {
    self.opened_at = None;
    core::mem::take(&mut self.items)
  }
}