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 two shipped citizens, and the claims about them that would otherwise be prose: that a group
//! with nothing in it is answered differently by the two, that the borrow and the erased forms both
//! measure, that a third citizen costs one impl — and that the word an author writes is the word the
//! citizen answers to.

use ingraph_codegen::aggregate::Measure as Word;

use super::{Counting, Measure, Summing};
use crate::Count;

/// `count(*)`, over a group a reader can count by eye.
#[test]
fn counting_answers_the_number_of_rows() {
  assert_eq!(Counting::new().fold(&["a", "b", "c"]), Count::new(3));
  assert_eq!(Counting::new().fold(&[7_u64]), Count::new(1));
}

/// **COUNTING DOES NOT READ AN ITEM**, so there is no item it cannot count — the blanket is the
/// citizen's whole character, pinned against a type this framework has never heard of and that
/// implements nothing.
#[test]
fn counting_folds_a_type_this_framework_never_heard_of() {
  struct Opaque;

  assert_eq!(Counting::new().fold(&[Opaque, Opaque]), Count::new(2));
}

/// **ZERO IS A TRUE ANSWER**, and counting is the only shipped measure that can give one: the count
/// of nothing needs no identity the currency has to name.
///
/// The case is unreachable through this framework's own road — a group with no rows is an absence
/// and no row is written for it — so what this pins is the citizen's HONESTY about an input it will
/// not be handed, not a path.
#[test]
fn counting_answers_zero_for_a_group_with_no_rows() {
  assert_eq!(Counting::new().fold(&[] as &[u64]), Count::new(0));
}

/// `sum(<column>)`, over a group a reader can add by hand.
#[test]
fn summing_adds_every_row() {
  assert_eq!(Summing::new().fold(&[10_u64, 20, 30]), 60);
  assert_eq!(Summing::new().fold(&[7_i32]), 7);
}

/// **THE FOLD STARTS FROM A REAL ITEM**, never from a zero: `Summing` asks for [`Add`](core::ops::Add)
/// and nothing else, so a currency with no nameable zero sums exactly as a `u64` does.
#[test]
fn summing_starts_from_the_first_row_rather_than_an_identity() {
  #[derive(Debug, Clone, Copy, PartialEq)]
  struct Cents(i64);

  impl core::ops::Add for Cents {
    type Output = Self;

    fn add(self, other: Self) -> Self {
      Self(self.0 + other.0)
    }
  }

  assert_eq!(
    Summing::new().fold(&[Cents(125), Cents(-25), Cents(400)]),
    Cents(500)
  );
}

/// **A SUM OF NOTHING IS NOT A ZERO.** The empty group aborts by name rather than manufacturing a
/// value that would be STORED and read back as a fact about the upstream — `iter::Sum`'s exact
/// failure, refused one family over and refused again here.
#[test]
#[should_panic(expected = "the `summing` measure was handed a group with no rows")]
fn summing_refuses_to_invent_a_total_for_a_group_with_no_rows() {
  let _ = Summing::new().fold(&[] as &[u64]);
}

/// The two citizens disagree exactly where the question does: one group's rows, two readings.
#[test]
fn the_two_shipped_measures_answer_the_same_group_differently() {
  let rows = [4_u64, 4, 4];

  assert_eq!(Counting::new().fold(&rows), Count::new(3));
  assert_eq!(Summing::new().fold(&rows), 12);
}

/// **THE CITIZEN'S NAME IS ITS BARE WORD**, and this is the pin that keeps the two halves from
/// drifting: the grammar's own shipped list on one side, the `name()` rows on the other.
///
/// Written against [`Word::SHIPPED`] rather than against literals, so a word renamed in the grammar
/// fails HERE rather than in a trace nobody reads.
#[test]
fn a_citizen_answers_to_the_word_the_grammar_spells_it_with() {
  assert_eq!(
    <Counting as Measure<u64>>::name(&Counting::new()),
    Word::SHIPPED[0]
  );
  assert_eq!(
    <Summing as Measure<u64>>::name(&Summing::new()),
    Word::SHIPPED[1]
  );
  assert_eq!(
    Word::SHIPPED.len(),
    2,
    "two citizens ship, and two words do"
  );
}

/// The words the grammar takes and the citizens this module ships are ONE SET — a bare word with no
/// citizen is a promise the emission cannot keep, and a citizen with no word is one nothing can
/// name.
#[test]
fn every_shipped_word_names_a_citizen_here() {
  let counting = Counting::new();
  let summing = Summing::new();

  for word in Word::SHIPPED {
    let named = Word::shipped(word).expect("a shipped word names a shipped fold");

    let answered = match named {
      Word::Counting => <Counting as Measure<u64>>::name(&counting),
      Word::Summing => <Summing as Measure<u64>>::name(&summing),
      Word::Declared(_) => unreachable!("a bare word is never a declared path"),
    };

    assert_eq!(answered, word);
  }
}

/// **A BORROWED MEASURE MEASURES** — what lets a call taking its measure BY VALUE be handed one that
/// lives somewhere else. Nothing is added: both rows forward.
///
/// Put through a door shaped like the one the recompute will be — `M` taken by value — because that
/// is the shape the impl exists for: a bare `counting.fold(…)` would resolve on the citizen and
/// never reach it.
#[test]
fn a_borrowed_measure_measures() {
  fn through<T, M: Measure<T>>(measure: M, items: &[T]) -> (M::Value, String) {
    let name = measure.name().to_owned();
    (measure.fold(items), name)
  }

  let counting = Counting::new();
  let summing = Summing::new();
  let rows = [2_u64, 3, 5];

  assert_eq!(
    through(&counting, &rows),
    (Count::new(3), "counting".to_owned())
  );
  assert_eq!(through(&summing, &rows), (10, "summing".to_owned()));
}

/// **THE TRAIT IS OBJECT SAFE, and the `?Sized` borrow is what makes an erased one usable.** No
/// emission needs this today — a declaration names its measure at COMPILE time, so the recompute's
/// call is static and monomorphizes — but a deployment holding a measure chosen at launch has the
/// road, and it costs one line that was already written for the borrow.
#[test]
fn an_erased_measure_measures() {
  let erased: &dyn Measure<u64, Value = u64> = &Summing::new();

  assert_eq!(erased.fold(&[1, 2, 3]), 6);
  assert_eq!(erased.name(), "summing");

  let boxed: Box<dyn Measure<u64, Value = Count>> = Box::new(Counting::new());

  assert_eq!(boxed.fold(&[9, 9]), Count::new(2));
}

/// **A THIRD CITIZEN IS ONE IMPL**, and nothing here widens to admit it: no arm, no match site, no
/// enum. This is the whole cost of the vocabulary being a trait — and it is the QUOTED-PATH escape's
/// own mechanism, written here as a downstream would write it.
#[test]
fn a_measure_this_module_never_heard_of_is_one_impl() {
  /// How many DISTINCT values the group holds — a measure this framework ships no word for, and
  /// whose answer is not its input's type.
  struct Distinct;

  impl<T: Ord + Clone + Send + Sync> Measure<T> for Distinct {
    type Value = u64;

    fn fold(&self, items: &[T]) -> u64 {
      let mut seen = items.to_vec();
      seen.sort_unstable();
      seen.dedup();
      u64::try_from(seen.len()).unwrap_or(u64::MAX)
    }

    fn name(&self) -> &str {
      "distinct"
    }
  }

  assert_eq!(Distinct.fold(&[1_u64, 2, 2, 3, 3, 3]), 3);
  assert_eq!(<Distinct as Measure<u64>>::name(&Distinct), "distinct");
}

/// A measure that folds exactly ONE item type writes the concrete impl and collides with nothing —
/// the blanket citizens above are blankets over `T` for THEIR OWN type, so they constrain no other
/// implementor.
#[test]
fn a_measure_over_one_item_type_needs_no_blanket() {
  struct Longest;

  impl Measure<String> for Longest {
    type Value = usize;

    fn fold(&self, items: &[String]) -> usize {
      items.iter().map(String::len).max().unwrap_or_default()
    }

    fn name(&self) -> &str {
      "longest"
    }
  }

  assert_eq!(
    Longest.fold(&["a".to_owned(), "abcd".to_owned(), "ab".to_owned()]),
    4
  );
}

/// A currency this framework ships no row for sums anyway, because there is no row to ship: what
/// `Summing` asks of a column is [`Add`](core::ops::Add), which a composite currency implements for
/// itself.
#[test]
fn a_composite_column_sums_without_a_framework_row() {
  #[derive(Debug, Clone, Copy, PartialEq)]
  struct Frames(u32, u64);

  impl core::ops::Add for Frames {
    type Output = Self;

    fn add(self, other: Self) -> Self {
      Self(self.0 + other.0, self.1 + other.1)
    }
  }

  assert_eq!(
    Summing::new().fold(&[Frames(2, 100), Frames(3, 250)]),
    Frames(5, 350)
  );
}

/// The citizens are SEALED and CONSTRUCTED — a literal `Counting` is not spellable downstream, so
/// the day one grows a field is not the day a caller breaks.
#[test]
fn a_citizen_is_reached_through_its_constructor() {
  assert_eq!(Counting::new(), Counting::default());
  assert_eq!(Summing::new(), Summing::default());
}