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
use core::{
  future::Future,
  pin::Pin,
  task::{Context, Poll},
  time::Duration,
};

use std::sync::{
  Arc, Mutex,
  atomic::{AtomicUsize, Ordering},
};

use jiff::SignedDuration;

use super::{BudgetSpent, SearchBudget, WalkBudget, WalkClock, tightened_budget, walk_within};

/// A future that is ready only after `polls` further polls, WAKING ITSELF each time.
///
/// The self-wake is what makes every race in this file deterministic and finite: a race that parked
/// would need a timer to unpark it, and a timer is what these tests exist to do without.
struct After<T> {
  polls: usize,
  out: Option<T>,
}

impl<T> After<T> {
  fn new(polls: usize, out: T) -> Self {
    Self {
      polls,
      out: Some(out),
    }
  }
}

impl<T: Unpin> Future for After<T> {
  type Output = T;

  fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
    if self.polls == 0 {
      return Poll::Ready(
        self
          .out
          .take()
          .expect("a walk is not polled after it answered"),
      );
    }
    self.polls -= 1;
    cx.waker().wake_by_ref();
    Poll::Pending
  }
}

/// A clock that fires after `polls` polls and REMEMBERS what it was handed.
///
/// The ledger is the assertion surface for the composition: what a clock is given is the number two
/// tiers agreed on, so a test reads the tightening off the clock rather than off the arithmetic it
/// already has its own suite for.
struct Scripted {
  polls: usize,
  handed: Arc<Mutex<Vec<Duration>>>,
  consulted: Arc<AtomicUsize>,
}

impl Scripted {
  fn new(polls: usize) -> (Self, Arc<Mutex<Vec<Duration>>>, Arc<AtomicUsize>) {
    let handed = Arc::new(Mutex::new(Vec::new()));
    let consulted = Arc::new(AtomicUsize::new(0));
    (
      Self {
        polls,
        handed: Arc::clone(&handed),
        consulted: Arc::clone(&consulted),
      },
      handed,
      consulted,
    )
  }
}

impl WalkClock for Scripted {
  fn elapsed<'a>(&'a self, budget: Duration) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
    self.consulted.fetch_add(1, Ordering::Relaxed);
    self
      .handed
      .lock()
      .expect("no test panics while holding this")
      .push(budget);
    Box::pin(After::new(self.polls, ()))
  }
}

/// A seat whose clock fires on its first poll — the wall a slow walk always loses to.
fn spent(budget: SearchBudget) -> (WalkBudget, Arc<Mutex<Vec<Duration>>>, Arc<AtomicUsize>) {
  let (clock, handed, consulted) = Scripted::new(0);
  (WalkBudget::new(clock, budget), handed, consulted)
}

/// A seat whose clock never fires inside a test — the wall a fast walk always beats.
fn patient(budget: SearchBudget) -> (WalkBudget, Arc<Mutex<Vec<Duration>>>, Arc<AtomicUsize>) {
  let (clock, handed, consulted) = Scripted::new(usize::MAX);
  (WalkBudget::new(clock, budget), handed, consulted)
}

/// **(I2) A WIRE BUDGET TIGHTENS AND NEVER LOOSENS** — the whole of the protective-numbers law in
/// four rows, read off the one function that spends it.
///
/// The row that carries the classification is the second: a request asking for five minutes against
/// a deployment that allows thirty seconds gets thirty seconds. A bound the requester can rewrite
/// binds nothing, so `min` is what a protective number composes with — never *explicit beats
/// ambient*.
#[test]
fn a_requests_budget_may_only_tighten_the_deployments() {
  let (short, long) = (SignedDuration::from_secs(5), SignedDuration::from_secs(30));

  assert_eq!(
    tightened_budget(Some(short), Some(long)),
    Some(short),
    "the ask, well inside the wall"
  );
  assert_eq!(
    tightened_budget(Some(SignedDuration::from_secs(300)), Some(long)),
    Some(long),
    "THE WALL — and no request may raise it",
  );
  assert_eq!(
    tightened_budget(Some(short), None),
    Some(short),
    "an absent deployment budget is informed openness, so the ask stands"
  );
  assert_eq!(
    tightened_budget(None, Some(long)),
    Some(long),
    "the deployment's, standing alone"
  );
  assert_eq!(tightened_budget(None, None), None, "nobody named one");
}

/// A NEGATIVE budget is *do not wait*, and `min` keeps it rather than repairing it — the reading of
/// a past deadline belongs where one is spent, not where two are composed.
#[test]
fn a_budget_already_past_is_carried_through_rather_than_clamped_here() {
  let past = SignedDuration::from_secs(-5);

  assert_eq!(
    tightened_budget(Some(past), Some(SignedDuration::from_secs(30))),
    Some(past),
  );
}

/// **THE CITIZEN IS DEFAULT-LESS**: an unnamed budget is [`None`] and never a shipped number, which
/// is what keeps *said nothing* and *asked for the shipped number* two different requests.
#[test]
fn an_unnamed_search_budget_names_nothing() {
  assert_eq!(SearchBudget::new().walk(), None);
  assert_eq!(SearchBudget::default(), SearchBudget::new());

  let named = SearchBudget::new().with_walk(SignedDuration::from_secs(30));
  assert_eq!(named.walk(), Some(SignedDuration::from_secs(30)));

  // AND BACK TO NOTHING, which is the in-place form's whole reason for taking an `Option`.
  let mut narrowed = named;
  narrowed.set_walk(None);
  assert_eq!(narrowed.walk(), None);
}

/// **ABSENCE IS IDENTITY, TWICE**: a walk with no seat, and a walk whose seat named no number, both
/// take the unwrapped road — and the second is the one that proves the clock is never even consulted.
#[tokio::test]
async fn a_walk_nobody_budgeted_is_awaited_with_no_clock_at_all() {
  let unseated = walk_within(None, None, "Bare", After::new(0, "answered")).await;
  assert_eq!(unseated, Ok("answered"));

  let (seat, handed, consulted) = patient(SearchBudget::new());
  let unnamed = walk_within(Some(&seat), None, "Bare", After::new(0, "answered")).await;

  assert_eq!(unnamed, Ok("answered"));
  assert_eq!(
    consulted.load(Ordering::Relaxed),
    0,
    "a seat that named no number still built a timer"
  );
  assert!(handed.lock().expect("no panic").is_empty());
}

/// **A WALK THAT OUTLIVES ITS BUDGET REFUSES BY NAME** — the keystone claim, and the one the whole
/// seat exists for.
#[tokio::test]
async fn a_walk_that_outlives_its_budget_refuses_by_name() {
  let wall = SignedDuration::from_secs(30);
  let (seat, handed, consulted) = spent(SearchBudget::new().with_walk(wall));

  let refused = walk_within(
    Some(&seat),
    None,
    "app::ClipText",
    After::new(64, "answered"),
  )
  .await
  .expect_err("a walk that never finishes cannot answer");

  assert_eq!(refused, BudgetSpent::new("app::ClipText", wall));
  assert_eq!(refused.tower(), "app::ClipText");
  assert_eq!(refused.budget(), wall);
  assert_eq!(consulted.load(Ordering::Relaxed), 1);
  assert_eq!(
    handed.lock().expect("no panic").as_slice(),
    [Duration::from_secs(30)]
  );

  // AND THE SENTENCE NAMES BOTH FACTS AN OPERATOR ACTS ON — never an empty answer.
  let said = refused.to_string();
  assert!(said.contains("app::ClipText"), "{said}");
  assert!(said.contains("did not finish"), "{said}");
  assert!(said.contains("nothing was answered"), "{said}");
}

/// **THE TIE GOES TO THE ANSWER** — a walk ready in the same wake as the clock is not thrown away.
#[tokio::test]
async fn a_walk_ready_in_the_same_wake_as_the_clock_keeps_its_answer() {
  let (seat, _, consulted) = spent(SearchBudget::new().with_walk(SignedDuration::from_secs(30)));

  let answered = walk_within(
    Some(&seat),
    None,
    "app::ClipText",
    After::new(0, "answered"),
  )
  .await;

  assert_eq!(answered, Ok("answered"));
  assert_eq!(
    consulted.load(Ordering::Relaxed),
    1,
    "the clock is built where a number was named, and the walk simply won"
  );
}

/// **TIER THREE'S SIDE, COMPOSED AT THE ENFORCEMENT POINT** — what the clock is handed is what
/// `tightened_budget` answered, which is the deployment-side caller landing.
#[tokio::test]
async fn the_clock_is_handed_the_number_the_two_tiers_agreed_on() {
  let wall = SignedDuration::from_secs(30);

  // A request well inside the wall narrows it.
  let (seat, handed, _) = patient(SearchBudget::new().with_walk(wall));
  let _ = walk_within(
    Some(&seat),
    Some(SignedDuration::from_secs(5)),
    "app::ClipText",
    After::new(0, "answered"),
  )
  .await;
  assert_eq!(
    handed.lock().expect("no panic").as_slice(),
    [Duration::from_secs(5)]
  );

  // A request OUTSIDE it does not, and that is the whole classification.
  let (seat, handed, _) = patient(SearchBudget::new().with_walk(wall));
  let _ = walk_within(
    Some(&seat),
    Some(SignedDuration::from_secs(300)),
    "app::ClipText",
    After::new(0, "answered"),
  )
  .await;
  assert_eq!(
    handed.lock().expect("no panic").as_slice(),
    [Duration::from_secs(30)]
  );

  // A request alone, against a deployment that named nothing, still binds — informed openness is
  // not a licence to ignore the ask.
  let (seat, handed, _) = patient(SearchBudget::new());
  let _ = walk_within(
    Some(&seat),
    Some(SignedDuration::from_secs(7)),
    "app::ClipText",
    After::new(0, "answered"),
  )
  .await;
  assert_eq!(
    handed.lock().expect("no panic").as_slice(),
    [Duration::from_secs(7)]
  );
}

/// **A PAST DEADLINE IS SPENT AS ZERO**, and the refusal still carries the number that was composed
/// rather than the clamp — the two are different facts and the clamp is the clock's.
#[tokio::test]
async fn a_budget_already_past_is_handed_to_the_clock_as_zero() {
  let past = SignedDuration::from_secs(-5);
  let (seat, handed, _) = spent(SearchBudget::new().with_walk(past));

  let refused = walk_within(
    Some(&seat),
    None,
    "app::ClipText",
    After::new(64, "answered"),
  )
  .await
  .expect_err("a budget already past cannot be waited out");

  assert_eq!(
    handed.lock().expect("no panic").as_slice(),
    [Duration::ZERO]
  );
  assert_eq!(
    refused.budget(),
    past,
    "the refusal carries the COMPOSED number"
  );
}

/// The seat prints its numbers and never its erased clock, exactly as the door prints whether one
/// was named.
#[test]
fn a_seat_debugs_as_its_numbers() {
  let (seat, _, _) = patient(SearchBudget::new().with_walk(SignedDuration::from_secs(30)));
  let printed = format!("{seat:?}");

  assert!(printed.contains("WalkBudget"), "{printed}");
  assert!(printed.contains("30s"), "{printed}");
  assert_eq!(
    seat.budget().walk(),
    Some(SignedDuration::from_secs(30)),
    "the seat hands its numbers back unchanged"
  );
}