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::{num::NonZeroUsize, time::Duration};

use super::{
  DEFAULT_SNAPSHOT_CAPACITY, DEFAULT_SNAPSHOT_DEPTH, DEFAULT_SNAPSHOT_TTL, PageToken,
  PageTokenRefusal, SnapshotKeeper,
};

/// The field word every test that does not care about crossing mints under.
const ROAD: &str = "travelSearchStretch";

fn want(rows: usize) -> NonZeroUsize {
  NonZeroUsize::new(rows).expect("a stretch of at least one row")
}

fn ranking(rows: u32) -> Vec<u32> {
  (0..rows).collect()
}

/// **THE THREE SHIPPED CONSTANTS ARE WHAT A BARE KEEPER RUNS AT** — tier one reached because
/// nothing above it was named, which is the three-tier law's own end-of-chain.
#[test]
fn a_bare_keeper_runs_at_the_shipped_constants() {
  let keeper = SnapshotKeeper::new();
  assert_eq!(keeper.capacity(), DEFAULT_SNAPSHOT_CAPACITY);
  assert_eq!(keeper.ttl(), DEFAULT_SNAPSHOT_TTL);
  assert_eq!(keeper.depth(), DEFAULT_SNAPSHOT_DEPTH);
}

/// **TIER TWO OVERRIDES EACH KNOB ON ITS OWN** — field by field, so a launch naming one number has
/// not silently restated the other two.
#[test]
fn a_launch_names_one_knob_and_the_others_stay_shipped() {
  let keeper = SnapshotKeeper::new().with_ttl(Duration::from_secs(9));
  assert_eq!(keeper.ttl(), Duration::from_secs(9));
  assert_eq!(keeper.capacity(), DEFAULT_SNAPSHOT_CAPACITY);
  assert_eq!(keeper.depth(), DEFAULT_SNAPSHOT_DEPTH);
}

/// **PAGE ONE, THE PAGE TOKEN, PAGE TWO** — disjoint and in the ranking's own order, with the
/// second stretch reached through the first's own claim and nothing re-computed.
#[test]
fn the_second_stretch_carries_on_where_the_first_stopped() {
  let keeper = SnapshotKeeper::new();
  let page_token = keeper.keep(ROAD, ranking(10));

  let first: super::Stretch<u32> = keeper
    .read(&page_token, ROAD, want(4))
    .expect("a live page token");
  assert_eq!(first.rows(), &[0, 1, 2, 3]);

  let next = *first.next().expect("six rows are still unread");
  assert_eq!(next.walked(), 4);

  let second: super::Stretch<u32> = keeper
    .read(&next, ROAD, want(4))
    .expect("a live page token");
  assert_eq!(second.rows(), &[4, 5, 6, 7]);

  let third: super::Stretch<u32> = keeper
    .read(
      second.next().expect("two rows are still unread"),
      ROAD,
      want(4),
    )
    .expect("a live page token");
  assert_eq!(third.rows(), &[8, 9]);

  // THE END IS AN ABSENT CLAIM, never a refusal: a client that walked the whole snapshot has an
  // answer, and a client whose page token was declined never got a stretch at all.
  assert!(third.next().is_none());
}

/// **A STRETCH ASKED FOR MORE THAN IS LEFT IS SHORT AND FINAL**, which is what makes the last
/// stretch of every snapshot the same shape whatever `first` was.
#[test]
fn a_stretch_wider_than_the_remainder_ends_the_walk() {
  let keeper = SnapshotKeeper::new();
  let page_token = keeper.keep(ROAD, ranking(3));
  let stretch: super::Stretch<u32> = keeper
    .read(&page_token, ROAD, want(50))
    .expect("a live page token");
  assert_eq!(stretch.rows(), &[0, 1, 2]);
  assert!(stretch.next().is_none());
}

/// **THE PAGE TOKEN SURVIVES ITS STRING**, which is the whole of what a client does with one.
#[test]
fn a_page_token_spelled_and_read_back_is_the_same_claim() {
  let keeper = SnapshotKeeper::new();
  let page_token = keeper.keep(ROAD, ranking(4));
  let spelled = page_token.to_string();
  let read: PageToken = spelled.parse().expect("this build's own spelling");
  assert_eq!(read, page_token);

  // BASE64URL, NO PADDING — the keyset cursor's alphabet, because it is the keyset cursor's own
  // implementation and there is exactly one in this crate.
  assert!(!spelled.contains('='), "{spelled}");
  assert!(!spelled.contains('+'), "{spelled}");
  assert!(!spelled.contains('/'), "{spelled}");
}

/// **A MALFORMED PAGE TOKEN IS REFUSED AT THE PARSE**, by name, before any keeper is consulted —
/// the untrusted-input obligation the keyset codec states and this token inherits.
#[test]
fn a_string_that_is_not_a_page_token_is_refused_at_the_parse() {
  for text in ["", "!!!!", "AAAA=", "AAAAAAAA"] {
    assert_eq!(
      text.parse::<PageToken>(),
      Err(PageTokenRefusal::Malformed),
      "{text}",
    );
  }
}

/// **A PAGE TOKEN OF THE RIGHT WIDTH AND THE WRONG VERSION IS STILL MALFORMED** — nothing inside
/// the frame is self-describing, so a version this build does not read is a frame it cannot read.
#[test]
fn a_frame_version_this_build_does_not_read_is_malformed() {
  let keeper = SnapshotKeeper::new();
  let page_token = keeper.keep(ROAD, ranking(2));
  let mut frame = page_token.frame();
  frame[0] = super::VERSION.wrapping_add(1);
  let forged = crate::cursor::text::encode(&frame);
  assert_eq!(
    forged.parse::<PageToken>(),
    Err(PageTokenRefusal::Malformed),
  );
}

/// **ANOTHER KEEPER'S PAGE TOKEN IS REFUSED BY NAME** — and refused BEFORE the lookup, so a
/// foreign serial can never land on one of ours.
#[test]
fn a_page_token_from_another_keeper_is_foreign() {
  let mine = SnapshotKeeper::new();
  let theirs = SnapshotKeeper::new();
  let _ = mine.keep(ROAD, ranking(4));
  let page_token = theirs.keep(ROAD, ranking(4));

  assert_eq!(
    mine.read::<u32>(&page_token, ROAD, want(2)),
    Err(PageTokenRefusal::Foreign),
  );
}

/// **A KEEPER'S CLONE IS THE SAME STORE UNDER THE SAME IDENTITY** — which is what makes a keeper
/// installable once and reachable from every read.
#[test]
fn a_clone_honours_the_original_keepers_page_tokens() {
  let keeper = SnapshotKeeper::new();
  let page_token = keeper.keep(ROAD, ranking(4));
  let handle = keeper.clone();
  let stretch: super::Stretch<u32> = handle.read(&page_token, ROAD, want(2)).expect("one store");
  assert_eq!(stretch.rows(), &[0, 1]);
}

/// **THE TTL REFUSES BY NAME**, and the refusal is `Expired` rather than `Unknown`: the snapshot
/// was still in the store and the clock is what took it, which is a different sentence for the
/// client and a different fact for whoever is reading the logs.
#[test]
fn a_snapshot_past_its_ttl_is_expired_by_name() {
  let keeper = SnapshotKeeper::new().with_ttl(Duration::ZERO);
  let page_token = keeper.keep(ROAD, ranking(4));
  assert_eq!(
    keeper.read::<u32>(&page_token, ROAD, want(2)),
    Err(PageTokenRefusal::Expired),
  );
}

/// **A TTL THAT HAS NOT PASSED KEEPS THE ANSWER** — the mutation half of the test above, without
/// which a keeper that expired everything would pass it.
#[test]
fn a_snapshot_inside_its_ttl_answers() {
  let keeper = SnapshotKeeper::new().with_ttl(Duration::from_secs(3600));
  let page_token = keeper.keep(ROAD, ranking(4));
  let stretch: super::Stretch<u32> = keeper
    .read(&page_token, ROAD, want(2))
    .expect("a live page token");
  assert_eq!(stretch.rows(), &[0, 1]);
}

/// **THE LRU EVICTS, AND THE EVICTED PAGE TOKEN REFUSES BY NAME** — `Unknown`, which is the
/// honest sentence for a snapshot the store gave up to make room.
#[test]
fn the_evicted_snapshot_is_unknown_by_name() {
  let keeper = SnapshotKeeper::new().with_capacity(want(2));
  let first = keeper.keep(ROAD, ranking(4));
  let second = keeper.keep(ROAD, ranking(4));
  assert_eq!(keeper.held(), 2);

  let third = keeper.keep(ROAD, ranking(4));
  assert_eq!(keeper.held(), 2, "the store stayed at its capacity");

  assert_eq!(
    keeper.read::<u32>(&first, ROAD, want(2)),
    Err(PageTokenRefusal::Unknown),
    "the least recently read snapshot is the one that went",
  );
  assert!(keeper.read::<u32>(&second, ROAD, want(2)).is_ok());
  assert!(keeper.read::<u32>(&third, ROAD, want(2)).is_ok());
}

/// **RECENCY IS READ AND NOT AGE**, which is the L of LRU and the one property a plain FIFO queue
/// would pass every other test without having: the OLDEST snapshot survives because somebody came
/// back to it, and the one nobody touched goes instead.
#[test]
fn the_snapshot_a_client_came_back_to_outlives_the_one_nobody_read() {
  let keeper = SnapshotKeeper::new().with_capacity(want(2));
  let oldest = keeper.keep(ROAD, ranking(4));
  let idle = keeper.keep(ROAD, ranking(4));

  // The client walking `oldest` comes back — which is what makes it the RECENTLY USED one.
  assert!(keeper.read::<u32>(&oldest, ROAD, want(1)).is_ok());

  let newest = keeper.keep(ROAD, ranking(4));

  assert!(
    keeper.read::<u32>(&oldest, ROAD, want(1)).is_ok(),
    "a client still walking its answer is the last one to lose it",
  );
  assert_eq!(
    keeper.read::<u32>(&idle, ROAD, want(1)),
    Err(PageTokenRefusal::Unknown),
  );
  assert!(keeper.read::<u32>(&newest, ROAD, want(1)).is_ok());
}

/// **A PAGE TOKEN HANDED TO ANOTHER FIELD IS REFUSED BY NAME**, and the sentence names both
/// fields.
///
/// The road word is what makes the type erasure safe rather than merely lucky: the downcast is
/// never attempted against a snapshot another field minted.
#[test]
fn a_page_token_handed_back_to_another_field_is_crossed() {
  let keeper = SnapshotKeeper::new();
  let page_token = keeper.keep("travelSearchKeysStretch", ranking(4));
  let refusal = keeper
    .read::<u32>(&page_token, "travelSearchStretch", want(2))
    .expect_err("one field's page token is not another's");

  assert_eq!(
    refusal,
    PageTokenRefusal::Crossed {
      minted_at: "travelSearchKeysStretch",
      asked_at: "travelSearchStretch".to_owned(),
    },
  );
  let said = refusal.to_string();
  assert!(said.contains("travelSearchKeysStretch"), "{said}");
  assert!(said.contains("travelSearchStretch"), "{said}");
}

/// **EVERY REFUSAL SAYS *ASK AGAIN* OR NAMES BOTH FIELDS** — the roster read as sentences, because
/// a named refusal a client cannot act on is a named refusal in name only.
#[test]
fn every_refusal_tells_the_client_what_to_do() {
  for refusal in [
    PageTokenRefusal::Foreign,
    PageTokenRefusal::Expired,
    PageTokenRefusal::Unknown,
  ] {
    let said = refusal.to_string();
    assert!(said.contains("ask the question again"), "{said}");
  }
  assert!(
    PageTokenRefusal::Malformed
      .to_string()
      .contains("not a page token"),
  );
}

/// **THE KEEPER TRUNCATES NOTHING** — the depth ceiling is the road's to spend through the
/// pipeline's one wall function, and a keeper that also cut would be a second authority for one
/// number.
#[test]
fn the_keeper_keeps_what_it_is_handed() {
  let keeper = SnapshotKeeper::new().with_depth(want(2));
  let page_token = keeper.keep(ROAD, ranking(5));
  let stretch: super::Stretch<u32> = keeper
    .read(&page_token, ROAD, want(9))
    .expect("a live page token");
  assert_eq!(stretch.rows().len(), 5);
  assert_eq!(
    keeper.depth(),
    want(2),
    "the ceiling is published, not applied"
  );
}

/// **THE SWEEP IS WHAT MAKES A TTL A MEMORY BOUND** rather than only a refusal: an aged snapshot is
/// gone from the store on the next operation, not merely declined when someone asks for it.
#[test]
fn an_aged_snapshot_leaves_the_store_without_being_asked_for() {
  let keeper = SnapshotKeeper::new().with_ttl(Duration::ZERO);
  let _ = keeper.keep(ROAD, ranking(4));
  let _ = keeper.keep(ROAD, ranking(4));
  assert_eq!(keeper.held(), 0);
}

/// **AN OFFSET AT THE END IS AN EMPTY STRETCH AND NOT A REFUSAL** — the boundary a client reaches
/// by asking for exactly as many rows as the snapshot holds and then following the claim.
#[test]
fn a_walk_that_ends_exactly_on_the_last_row_has_no_next() {
  let keeper = SnapshotKeeper::new();
  let page_token = keeper.keep(ROAD, ranking(4));
  let stretch: super::Stretch<u32> = keeper
    .read(&page_token, ROAD, want(4))
    .expect("a live page token");
  assert_eq!(stretch.rows(), &[0, 1, 2, 3]);
  assert!(stretch.next().is_none());
}

/// **TWO KEEPERS NEVER SHARE AN IDENTITY**, which is what the `Foreign` refusal rests on.
#[test]
fn two_keepers_minted_together_are_distinct() {
  let identities: std::collections::HashSet<_> =
    (0..64).map(|_| SnapshotKeeper::new().identity).collect();
  assert_eq!(identities.len(), 64);
}