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
//! **A COMPOSITE order term: per-segment COLUMNS, one slot, and the segments inside its bytes.**
//!
//! ```text
//! term      identity "at", column "at", segments [secs, nanos]      width 2
//! ORDER BY  "at_secs" ASC, "at_nanos" ASC                            one entry per COLUMN
//! slot      8 bytes of seconds, then 4 of nanoseconds                one slot, checked as a pair
//! ```
//!
//! # Why the segments are inside a slot rather than beside it
//!
//! A term is ONE subject and a cursor holds one slot per term, and both halves of that are load
//! bearing rather than economical. The identity is the RECORD FIELD's own name and a declaration
//! cannot give two columns one identity, so two terms for one field would need an identity nothing
//! declared — and the slot is the VALUE the boundary row held, so splitting it would split an
//! instant into halves nothing on the page ever holds separately.
//!
//! What the SQL family does with the same term is flatten it: the `ORDER BY` renders one entry per
//! column and the keyset compares them as a row value, which is the only-eq law arriving at the
//! ordering seam. A document family nests instead and reads the column alone. Two readings of one
//! term, rather than two term lists.
//!
//! # The pair is CHECKED coming back
//!
//! `read_cursor` recomposes through [`Timestamp::from_parts`](crate::Timestamp::from_parts) — the
//! third caller of one authority, the SQL decode and the MongoDB read being the other two — so a
//! pair jiff would have normalised is refused here as it is refused there. *Returning a plausible
//! value for bytes this type did not write is how a forged cursor becomes a page*, and a composite
//! has more ways to be plausible than a scalar: eleven bytes, a nanosecond past the second, a
//! second past the domain.

use super::super::{Cursor, CursorError, CursorValue, OrderTerm, TermName};
use crate::{ColumnKind, FieldName, OrderDirection, Timestamp};

/// The instant column this module pages over.
const AT: &TermName = TermName::new("at");

/// The term an emission writes for it: [`spanning`](OrderTerm::spanning), which is the ONE spelling
/// every column takes — a scalar lands back on the empty answer and a composite states its parts.
fn instant() -> OrderTerm {
  OrderTerm::spanning(
    AT,
    FieldName::new("at"),
    <Timestamp as ColumnKind>::SEGMENTS,
    <Timestamp as ColumnKind>::ORDER,
    OrderDirection::Desc,
  )
}

/// The key tail that makes the order total.
fn id() -> OrderTerm {
  OrderTerm::new(
    TermName::new("id"),
    FieldName::new("id"),
    OrderDirection::Asc,
  )
}

fn at(second: i64, nanosecond: i32) -> Timestamp {
  Timestamp::from_parts(second, nanosecond).expect("a legal instant")
}

/// **ONE term, TWO columns.** The width is what the `ORDER BY` iterates and what the keyset brackets
/// its operand by, so the two cannot disagree about the width of one subject.
#[test]
fn a_composite_term_is_one_subject_of_several_columns() {
  let term = instant();
  assert_eq!(term.width(), 2);
  assert_eq!(term.segments().len(), 2);
  assert_eq!(
    term.column(),
    FieldName::new("at"),
    "the FIELD's name, which the columns are rendered beneath rather than a column of its own"
  );
  assert_eq!(id().width(), 1, "and a scalar is the empty answer");
}

/// **ONE slot, whose bytes are the segments.** Twelve of them, in the order the type states its
/// parts, which is the same order its columns are declared in.
#[test]
fn the_slot_carries_every_segment() {
  let mut bytes = Vec::new();
  at(7, 250).write_cursor(&mut bytes);

  assert_eq!(bytes.len(), 12, "eight of seconds and four of nanoseconds");
  assert_eq!(&bytes[..8], &7i64.to_be_bytes());
  assert_eq!(&bytes[8..], &250i32.to_be_bytes());
}

/// **The RESUME.** A cursor minted at a boundary row decodes to the same values and resumes the
/// order it was minted under — the whole round trip a page over a composite subject takes.
#[test]
fn a_composite_boundary_resumes_its_own_order() {
  let order = [instant(), id()];
  let boundary = Cursor::at(
    &order,
    [Some(Value::At(at(1_700_000_000, 42))), Some(Value::Id(9))],
  );

  let text = boundary.encode();
  let read = Cursor::<Value>::decode(&text).expect("this build minted it");

  assert_eq!(read, boundary, "the frame round-trips");
  assert_eq!(
    read.resume(&order).expect("the same order"),
    [Some(Value::At(at(1_700_000_000, 42))), Some(Value::Id(9))],
    "both segments of the instant survive, as one value"
  );
}

/// A cursor minted under ANOTHER order is refused before any SQL renders — and a composite term is
/// no exception, its identity being folded in exactly as a scalar's is.
#[test]
fn a_composite_cursor_is_refused_under_another_order() {
  let order = [instant(), id()];
  let boundary = Cursor::at(&order, [Some(Value::At(at(1, 0))), Some(Value::Id(9))]);

  let other = [
    OrderTerm::spanning(
      AT,
      FieldName::new("at"),
      <Timestamp as ColumnKind>::SEGMENTS,
      <Timestamp as ColumnKind>::ORDER,
      OrderDirection::Asc,
    ),
    id(),
  ];

  assert!(matches!(
    boundary.resume(&other),
    Err(CursorError::Order(_))
  ));
}

/// **A short pair is refused rather than zero-extended into a plausible instant**, which is the
/// discipline every fixed-width row follows applied to a value of two of them.
#[test]
fn a_truncated_pair_is_not_an_instant() {
  for short in [&[0u8; 11][..], &[0; 13][..], &[]] {
    assert!(
      <Timestamp as CursorValue>::read_cursor(short).is_none(),
      "a client's {} bytes are not an instant",
      short.len()
    );
  }
}

/// **A pair the TYPE would have normalised is refused too.** A nanosecond of a full second is not a
/// value `from_parts` admits, so the codec answers `None` and the decode raises at the slot's own
/// position — where a lenient recomposition would resume the page at an instant no row holds.
#[test]
fn a_pair_the_type_normalises_is_refused() {
  let mut bytes = Vec::new();
  bytes.extend_from_slice(&7i64.to_be_bytes());
  bytes.extend_from_slice(&1_000_000_000i32.to_be_bytes());

  assert!(<Timestamp as CursorValue>::read_cursor(&bytes).is_none());
}

/// The record's own sum over its orderable columns — one arm per paged column, which is what an
/// expansion emits and what makes a heterogeneous order one `V`.
#[derive(Debug, Clone, PartialEq)]
enum Value {
  At(Timestamp),
  Id(i64),
}

/// A one-byte TAG of its own, which the frame does not supply: a slot is delimited and its contents
/// are the record's vocabulary, so the sum is the party that knows which arm it wrote.
impl CursorValue for Value {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    match self {
      Self::At(instant) => {
        out.push(0);
        instant.write_cursor(out);
      }
      Self::Id(id) => {
        out.push(1);
        id.write_cursor(out);
      }
    }
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let (tag, rest) = bytes.split_first()?;
    match tag {
      0 => Timestamp::read_cursor(rest).map(Self::At),
      1 => i64::read_cursor(rest).map(Self::Id),
      _ => None,
    }
  }
}