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 DOOR, read from both sides: what a list decodes into, and what the schema shows a client.

use async_graphql::{EmptyMutation, EmptySubscription, InputType, Object, Pos, Schema, Value};

use super::MediaOrderBy;
use crate::{
  OrderDirection::{Asc, Desc},
  Orderings, ToSubjectPath,
};

/// The wire form of a client's list, built from the terms themselves so the fixture cannot drift
/// from the field names the derive renders.
fn written(terms: &[MediaOrderBy]) -> Value {
  Value::List(terms.iter().map(InputType::to_value).collect())
}

fn decode(terms: &[MediaOrderBy]) -> Result<Orderings<MediaOrderBy>, String> {
  InputType::parse(Some(written(terms)))
    .map_err(|error| error.into_server_error(Pos::default()).message)
}

/// The subjects an order holds, in the sequence it holds them.
fn subjects(order: &Orderings<MediaOrderBy>) -> Vec<String> {
  order
    .terms()
    .map(|term| term.subject_path().to_string())
    .collect()
}

/// A subject named twice is refused, and the refusal names BOTH positions and the subject — the
/// three facts a client needs to find the term to delete.
///
/// REFUSAL rather than a silent drop: the two backends do not agree about what the second term
/// means, so the only answer that reads the same everywhere is that the list is not one this
/// framework accepts. The direction is no part of it — `title ASC` then `title DESC` is the same
/// subject twice, and the second one is the one that cannot run.
#[test]
fn a_repeated_subject_is_refused_at_the_term_that_repeats_it() {
  let refusal = decode(&[
    MediaOrderBy::Title(Asc),
    MediaOrderBy::Name(Desc),
    MediaOrderBy::Title(Desc),
  ])
  .expect_err("the third term repeats the first");

  assert!(
    refusal.contains("ordering term 2 names `title`, which term 0 already orders by"),
    "the refusal names the repeat's position, the subject, and the term it repeats: {refusal}"
  );

  // The same subject ADJACENT to itself, and in one direction, is the same refusal — nothing here
  // turns on distance or on the directions differing.
  let refusal = decode(&[MediaOrderBy::Title(Asc), MediaOrderBy::Title(Asc)])
    .expect_err("the second term repeats the first");
  assert!(
    refusal.contains("ordering term 1 names `title`, which term 0 already orders by"),
    "{refusal}"
  );
}

/// `cover.title` and `title` are DISTINCT subjects, and so are `cover.title` and `cover.duration` —
/// the identity is the whole path, not its head and not the column at its tail.
///
/// This is the pair the rule exists to keep legal. A uniqueness key over the FIRST SEGMENT would
/// refuse the second order here, and a key over the LAST would refuse the first.
#[test]
fn a_shared_segment_is_not_a_shared_subject() {
  let order = decode(&[MediaOrderBy::CoverTitle(Asc), MediaOrderBy::Title(Desc)])
    .expect("a nested subject and a root subject are two subjects");
  assert_eq!(subjects(&order), ["cover.title", "title"]);

  let order = decode(&[
    MediaOrderBy::CoverTitle(Asc),
    MediaOrderBy::CoverDuration(Desc),
  ])
  .expect("two subjects under one prefix are two subjects");
  assert_eq!(subjects(&order), ["cover.title", "cover.duration"]);
}

/// The SEQUENCE is the semantics, so it is what survives the decode: the terms come back in the
/// order they were written, not in the order the subjects sort.
///
/// Four terms, written so that no reordering rule — alphabetical by subject, by variant, by
/// insertion into a plain hash map — reproduces the written sequence by accident.
#[test]
fn the_sequence_a_client_wrote_is_the_sequence_that_survives() {
  let order = decode(&[
    MediaOrderBy::Name(Desc),
    MediaOrderBy::CoverTitle(Asc),
    MediaOrderBy::Id(Asc),
    MediaOrderBy::Title(Desc),
  ])
  .expect("four distinct subjects");

  assert_eq!(subjects(&order), ["name", "cover.title", "id", "title"]);
  assert_eq!(
    order.into_terms(),
    [
      MediaOrderBy::Name(Desc),
      MediaOrderBy::CoverTitle(Asc),
      MediaOrderBy::Id(Asc),
      MediaOrderBy::Title(Desc),
    ],
    "the terms themselves travel with their directions, in the written sequence"
  );
}

/// `[]` is the EMPTY ORDER and not a refusal — the state a query that wrote no term is already in.
///
/// What requires a written order is a PAGE, and the query lane that owns paging is where that is
/// enforced. Refusing here would refuse an unpaged query the unordered semantics SQL already has.
#[test]
fn an_empty_list_is_the_empty_order() {
  let order = decode(&[]).expect("an empty list is a legal order");
  assert!(order.is_empty());
  assert_eq!(order.len(), 0);
  assert_eq!(subjects(&order), Vec::<String>::new());
  assert!(order.into_terms().is_empty());
}

/// A term naming the KEY is legal, and it is the interplay the design settled: the emitted
/// `complete()` MOVES the key into the position a client asked for rather than appending a second
/// one, so the key is an ordinary subject here and refusing it would be refusing twice.
#[test]
fn a_term_naming_the_key_is_legal() {
  let order = decode(&[MediaOrderBy::Title(Asc), MediaOrderBy::Id(Desc)])
    .expect("naming the key is naming a column");
  assert_eq!(subjects(&order), ["title", "id"]);
  assert_eq!(
    order.term(MediaOrderBy::Id(Asc).subject_path()),
    Some(&MediaOrderBy::Id(Desc)),
    "the subject is keyed on the column and not on the direction, so the lookup finds the term \
     that was actually written"
  );
}

/// GraphQL's own list input coercion: a lone value is the one-element list. Mirrored from `Vec`'s
/// decode, so a client that may write `order: {title: ASC}` against an array keeps being able to.
#[test]
fn a_lone_term_coerces_to_the_one_term_list() {
  let order: Orderings<MediaOrderBy> =
    InputType::parse(Some(InputType::to_value(&MediaOrderBy::Title(Asc))))
      .expect("a lone term is a one-term order");
  assert_eq!(subjects(&order), ["title"]);
}

struct Query;

#[Object]
impl Query {
  /// The face under test.
  async fn media(&self, order: Option<Orderings<MediaOrderBy>>) -> String {
    order.map_or_else(
      || String::from("none"),
      |order| {
        order
          .terms()
          .map(|term| term.subject_path().to_string())
          .collect::<Vec<_>>()
          .join(",")
      },
    )
  }

  /// The CONTROL: the same terms behind a plain `Vec`, which is what the wrapper has to be
  /// indistinguishable from in SDL.
  async fn control(&self, order: Option<Vec<MediaOrderBy>>) -> usize {
    order.map_or(0, |order| order.len())
  }
}

fn schema() -> Schema<Query, EmptyMutation, EmptySubscription> {
  Schema::new(Query, EmptyMutation, EmptySubscription)
}

/// **The wrapper is not a schema name.** The argument renders as `[MediaOrderBy!]` — the array the
/// design ruled — and the registry gains the term's input object and nothing else.
///
/// The control argument is the proof rather than a second opinion: a `Vec` of the same term renders
/// the identical type reference, so a schema review cannot tell the decode is there. A wrapper that
/// registered a type of its own would be a second thing for a client to learn about an order that
/// has not changed, and it would show up on both lines below.
#[test]
fn the_wrapper_renders_as_the_array_and_declares_no_type_of_its_own() {
  let sdl = schema().sdl();

  let argument = |field: &str| {
    sdl
      .lines()
      .map(str::trim)
      .find(|line| line.starts_with(field))
      .unwrap_or_else(|| panic!("`{field}` is a field of the schema: {sdl}"))
      .to_owned()
  };
  assert_eq!(argument("media("), "media(order: [MediaOrderBy!]): String!");
  assert_eq!(
    argument("control("),
    "control(order: [MediaOrderBy!]): Int!"
  );

  assert_eq!(
    <Orderings<MediaOrderBy> as InputType>::type_name(),
    "[MediaOrderBy!]",
    "the wrapper PRESENTS a list type reference, which is why no name of its own reaches the SDL"
  );
  assert_eq!(
    <Option<Orderings<MediaOrderBy>> as InputType>::qualified_type_name(),
    <Option<Vec<MediaOrderBy>> as InputType>::qualified_type_name(),
    "and it is the same reference the `Vec` presents, nullability included"
  );

  let inputs: Vec<&str> = sdl
    .lines()
    .filter_map(|line| line.strip_prefix("input "))
    .filter_map(|line| line.strip_suffix(" {"))
    .collect();
  assert_eq!(
    inputs,
    ["MediaOrderBy @oneOf"],
    "one input type, and it is the TERM's — nothing is registered for the wrapper"
  );
}

/// The refusal reaches a client as an error POSITIONED at the argument it came in through, which is
/// what makes "which term" answerable at all — the message carries the index inside the list, the
/// location carries where the list was written.
#[tokio::test]
async fn the_refusal_reaches_a_client_positioned_at_the_argument() {
  let response = schema()
    .execute("{ media(order: [{title: ASC}, {name: DESC}, {title: DESC}]) }")
    .await;

  let error = response
    .errors
    .first()
    .expect("the repeated subject is refused");
  assert!(
    error
      .message
      .contains("ordering term 2 names `title`, which term 0 already orders by"),
    "{}",
    error.message
  );
  assert_eq!(
    error.locations.first().map(|at| at.column),
    Some(16),
    "positioned at the order argument's value"
  );

  // The same schema accepts the list with the repeat removed, so what was refused is the repeat.
  let response = schema()
    .execute("{ media(order: [{title: ASC}, {name: DESC}]) }")
    .await;
  assert!(response.errors.is_empty(), "{:?}", response.errors);
  assert_eq!(
    response.data.to_string(),
    r#"{media: "title,name"}"#,
    "and the accepted order keeps the sequence the client wrote"
  );
}