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 super::*;
use crate::primitives::mediatime::tests::range;

/// The width is SIX columns across five segments, and the middle one is the timebase's own answer.
#[test]
fn a_range_spans_its_value_columns_and_its_derived_pair() {
  let shapes = <MediaTimeRange as ColumnKind>::SEGMENTS;

  assert_eq!(shapes.len(), 5);
  assert!(matches!(shapes[2], ColumnShape::Composite { segments, .. }
    if core::ptr::eq(segments, <Timebase as ColumnKind>::SEGMENTS)));

  let names: Vec<_> = shapes
    .iter()
    .map(|shape| {
      shape
        .field()
        .expect("every segment names a field")
        .declared()
        .as_str()
    })
    .collect();
  assert_eq!(
    names,
    [
      "start_pts",
      "end_pts",
      "timebase",
      "start_nanos",
      "end_nanos"
    ]
  );
}

/// The cursor carries both counts and the shared timebase — three values, twenty-four bytes.
#[test]
fn the_cursor_carries_the_value_columns() {
  let mut bytes = Vec::new();
  range(100, 250, 1, 90_000).write_cursor(&mut bytes);

  assert_eq!(bytes.len(), 24);

  let read = <MediaTimeRange as CursorValue>::read_cursor(&bytes).expect("its own bytes");
  assert_eq!(read.get().start_pts(), 100);
  assert_eq!(read.get().end_pts(), 250);
  assert_eq!(read, range(100, 250, 1, 90_000));
}

/// A forged cursor is refused on WIDTH, on the timebase's own rules, and on the ordering invariant —
/// the last of which no width check would catch.
#[test]
fn a_forged_cursor_is_refused_rather_than_read() {
  for forged in [[0u8; 0].as_slice(), &[0; 16], &[0; 23], &[0; 25]] {
    assert_eq!(
      <MediaTimeRange as CursorValue>::read_cursor(forged),
      None,
      "{forged:?}"
    );
  }

  // Twenty-four well-formed bytes whose endpoints run BACKWARDS: start 250, end 100, at 1/90000.
  let mut inverted = Vec::new();
  CursorValue::write_cursor(&250i64, &mut inverted);
  CursorValue::write_cursor(&100i64, &mut inverted);
  CursorValue::write_cursor(&Timebase::new(mt::Timebase::MPEG_90K), &mut inverted);

  assert_eq!(inverted.len(), 24, "the refusal is not about the width");
  assert_eq!(
    <MediaTimeRange as CursorValue>::read_cursor(&inverted),
    None
  );
}

/// The ordering invariant is a rule the DATABASE can break, so the reader states it rather than
/// assuming it — and says so when it is broken.
#[test]
fn an_inverted_pair_is_not_a_range() {
  assert_eq!(
    InvertedMediaTimeRange.to_string(),
    "a stored range's end must not precede its start"
  );
  assert!(mt::TimeRange::try_new(250, 100, mt::Timebase::MPEG_90K).is_none());
}

/// **A range with one unplaceable endpoint keeps its value**, which is the overflow posture per
/// ENDPOINT rather than per range.
#[test]
fn an_unplaceable_endpoint_costs_the_value_nothing() {
  let extreme = range(0, i64::MAX, 1, 1);

  assert!(
    extreme.start().to_nanos().is_ok(),
    "the start still has a position"
  );
  assert!(extreme.end().to_nanos().is_err(), "the end has none");
  assert!(
    extreme.duration_nanos().is_err(),
    "and so the length has none"
  );

  let mut bytes = Vec::new();
  extreme.write_cursor(&mut bytes);
  assert_eq!(
    <MediaTimeRange as CursorValue>::read_cursor(&bytes),
    Some(extreme),
    "the cursor carries the value, which is exact"
  );
}

/// The length is `end - start` over the derived positions, which is what the duration facet compares.
#[test]
fn the_length_is_the_difference_of_the_two_positions() {
  assert_eq!(
    range(0, 90_000, 1, 90_000).duration_nanos(),
    Ok(1_000_000_000)
  );
  assert_eq!(range(100, 250, 1, 90_000).duration_nanos(), Ok(1_666_666));
  assert_eq!(range(5, 5, 1, 1).duration_nanos(), Ok(0));
}

/// **The SEQUENCE those six columns mean** — the start instant's four leaves, then the end's two.
///
/// Pinned as ORDINALS rather than as prose, because the numbering is what every reader downstream
/// spends: a level holds the leaf ordinal its `OrderLevel` named, and the vocabulary below is asked
/// at that same number.
#[test]
fn the_order_is_the_start_instant_then_the_end_one() {
  let order: Vec<usize> = <MediaTimeRange as ColumnKind>::ORDER
    .iter()
    .map(|level| level.leaf())
    .collect();

  // start_nanos, start_pts, timebase_num, timebase_den, end_nanos, end_pts.
  assert_eq!(order, [4, 0, 2, 3, 5, 1]);
}

/// **Every leaf named ONCE**, which is what makes the sequence a permutation rather than a walk.
///
/// The shared timebase is the reason this can be asserted at all: a composition of two four-leaf
/// instant sequences would name `num` and `den` twice, and the second naming could separate no two
/// rows — the pair being fixed by the start half above it.
#[test]
fn the_sequence_is_a_permutation_of_the_leaves() {
  let mut named: Vec<usize> = <MediaTimeRange as ColumnKind>::ORDER
    .iter()
    .map(|level| level.leaf())
    .collect();
  named.sort_unstable();

  assert_eq!(named, [0, 1, 2, 3, 4, 5]);
  assert_eq!(named.len(), crate::width(SEGMENTS));
}

/// **The vocabulary, at every leaf** — in the SEGMENT numbering, the permutation being spent before
/// this is asked.
#[test]
fn a_range_answers_through_its_own_published_vocabulary() {
  let span = range(90_000, 180_000, 1, 90_000);
  let leaf = |at| crate::OrderLeaves::leaf(&span, at);

  assert_eq!(leaf(0), Some(MediaTimeRangeLeaf::StartPts(90_000)));
  assert_eq!(leaf(1), Some(MediaTimeRangeLeaf::EndPts(180_000)));
  assert_eq!(leaf(2), Some(MediaTimeRangeLeaf::TimebaseNum(1)));
  assert_eq!(leaf(3), Some(MediaTimeRangeLeaf::TimebaseDen(90_000)));
  assert_eq!(leaf(4), Some(MediaTimeRangeLeaf::StartNanos(1_000_000_000)));
  assert_eq!(leaf(5), Some(MediaTimeRangeLeaf::EndNanos(2_000_000_000)));
  assert_eq!(
    leaf(6),
    None,
    "a leaf past the type is absent rather than a panic"
  );
}

/// **The timebase leaves are the REDUCED pair**, which is what the columns hold and what the write
/// binds. A boundary carrying the DECLARED pair would compare against a value no column has.
#[test]
fn the_timebase_leaves_are_the_reduced_pair() {
  let declared = range(100, 250, 2, 180_000);
  let leaf = |at| crate::OrderLeaves::leaf(&declared, at);

  assert_eq!(leaf(2), Some(MediaTimeRangeLeaf::TimebaseNum(1)));
  assert_eq!(leaf(3), Some(MediaTimeRangeLeaf::TimebaseDen(90_000)));
}

/// **THE DERIVED PAIR IS RECOMPUTED PER ENDPOINT, and one absence does not cost the other.**
///
/// The posture the write takes, read at the boundary: the bind loops the two endpoints and writes
/// `NULL` for whichever has no `i64` nanosecond position, so a level over the other one still has the
/// value the statement sorted by. Routing both leaves through `MediaTimeRange::to_nanos` — which
/// refuses when EITHER end overflows — would answer `None` for a start the write bound exactly.
#[test]
fn each_derived_leaf_answers_for_its_own_endpoint() {
  let half = range(0, i64::MAX, 1, 1);
  let leaf = |at| crate::OrderLeaves::leaf(&half, at);

  assert!(
    half.to_nanos().is_err(),
    "the PAIR has no position, which is the answer this must not inherit"
  );
  assert_eq!(
    leaf(4),
    Some(MediaTimeRangeLeaf::StartNanos(0)),
    "the start's own position is exact"
  );
  assert_eq!(leaf(5), None, "and only the end's is absent");
  assert_eq!(
    leaf(0),
    Some(MediaTimeRangeLeaf::StartPts(0)),
    "the value leaves are exact whatever either position is"
  );
  assert_eq!(leaf(1), Some(MediaTimeRangeLeaf::EndPts(i64::MAX)));

  // And the other side of the ceiling, which only a RANGE can be on: a start with no position and an
  // end with one.
  let backwards = range(i64::MIN, 0, 1, 1);
  assert_eq!(crate::OrderLeaves::leaf(&backwards, 4), None);
  assert_eq!(
    crate::OrderLeaves::leaf(&backwards, 5),
    Some(MediaTimeRangeLeaf::EndNanos(0))
  );
}

/// **A leaf at every declared level**, which is the pairing `ColumnKind::ORDER`'s note states: a
/// level that could not be read would be a page with no boundary to resume at.
#[test]
fn the_vocabulary_is_as_wide_as_the_sequence() {
  let span = range(100, 250, 1, 90_000);
  for level in <MediaTimeRange as ColumnKind>::ORDER {
    assert!(
      crate::OrderLeaves::leaf(&span, level.leaf()).is_some(),
      "every declared level of a citizen has a leaf to compare"
    );
  }
}

/// **A LEAF's own cursor position**: which leaf, then that leaf's own bytes — and a byte naming no
/// leaf is refused rather than read as the nearest one.
#[test]
fn a_leaf_writes_its_tag_and_reads_its_own_bytes_back() {
  for leaf in [
    MediaTimeRangeLeaf::StartPts(100),
    MediaTimeRangeLeaf::EndPts(250),
    MediaTimeRangeLeaf::TimebaseNum(1),
    MediaTimeRangeLeaf::TimebaseDen(90_000),
    MediaTimeRangeLeaf::StartNanos(1_111_111),
    MediaTimeRangeLeaf::EndNanos(2_777_777),
  ] {
    let mut bytes = Vec::new();
    leaf.write_cursor(&mut bytes);
    assert_eq!(
      <MediaTimeRangeLeaf as CursorValue>::read_cursor(&bytes),
      Some(leaf),
      "{leaf:?}"
    );
  }

  assert_eq!(
    <MediaTimeRangeLeaf as CursorValue>::read_cursor(&[]),
    None,
    "an empty slot names no leaf"
  );
  assert_eq!(
    <MediaTimeRangeLeaf as CursorValue>::read_cursor(&[6, 0, 0, 0, 0, 0, 0, 0, 0]),
    None,
    "and neither does a tag past the vocabulary"
  );
}

/// **The two vocabularies are DISTINCT byte streams**, so a slot minted for one citizen cannot be
/// read as the other's — the tags are per type and a range's leaf `4` is not an instant's.
#[test]
fn a_leafs_bytes_are_its_own_widths() {
  let mut narrow = Vec::new();
  MediaTimeRangeLeaf::TimebaseNum(1).write_cursor(&mut narrow);
  let mut wide = Vec::new();
  MediaTimeRangeLeaf::StartPts(1).write_cursor(&mut wide);

  assert_eq!(narrow.len(), 1 + size_of::<i32>());
  assert_eq!(wide.len(), 1 + size_of::<i64>());
}