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::ErrorCode;

/// Every word this build publishes, walked as a list rather than asserted one at a time — the
/// vocabulary IS the contract, so a round that adds a word touches this fixture and a round that
/// silently re-points one cannot.
const VOCABULARY: &[(ErrorCode, &str)] = &[
  (ErrorCode::RepeatedOrderSubject, "REPEATED_ORDER_SUBJECT"),
  (
    ErrorCode::AmbiguousPageDirection,
    "AMBIGUOUS_PAGE_DIRECTION",
  ),
  (ErrorCode::UnusableCursor, "UNUSABLE_CURSOR"),
  (ErrorCode::StoreRefused, "STORE_REFUSED"),
  (ErrorCode::UnsupportedFilter, "UNSUPPORTED_FILTER"),
  (ErrorCode::UnrenderableOrder, "UNRENDERABLE_ORDER"),
  (ErrorCode::UnpageableOrder, "UNPAGEABLE_ORDER"),
  (ErrorCode::UnreadableRow, "UNREADABLE_ROW"),
  (ErrorCode::OversizedSkip, "OVERSIZED_SKIP"),
  (ErrorCode::UnwrittenArtifact, "UNWRITTEN_ARTIFACT"),
  // `UNUSABLE_ADDRESS` was minted and never joined this list. Added with the transport's four
  // rather than left out, because the fixture's own note calls the walk the contract: a word absent
  // from it is a word the injectivity and casing claims below were never made about.
  (ErrorCode::UnusableAddress, "UNUSABLE_ADDRESS"),
  (ErrorCode::UnreachableSource, "UNREACHABLE_SOURCE"),
  (ErrorCode::UnreachableNode, "UNREACHABLE_NODE"),
  (ErrorCode::RequestDropped, "REQUEST_DROPPED"),
  (ErrorCode::RequestTimedOut, "REQUEST_TIMED_OUT"),
];

/// The words are what a client matches on, so they are pinned LITERALLY here: a rename of the Rust
/// variant is free and a change to the string below is a breaking change to every client.
#[test]
fn each_code_renders_the_word_a_client_matches_on() {
  for (code, word) in VOCABULARY {
    assert_eq!(code.as_str(), *word);
    assert_eq!(code.to_string(), *word, "the rendering is the word itself");
  }
}

/// No two codes share a word. A vocabulary is only a contract while it is injective — two refusals
/// under one word would tell a client one thing about two different mistakes.
#[test]
fn no_two_codes_share_a_word() {
  let mut seen: Vec<&str> = VOCABULARY.iter().map(|(_, word)| *word).collect();
  let written = seen.len();
  seen.sort_unstable();
  seen.dedup();
  assert_eq!(seen.len(), written, "each code has a word of its own");
}

/// `SCREAMING_SNAKE_CASE`, which is GraphQL's own convention for a machine-read constant — asserted
/// over the whole vocabulary so a word added in a lower case never reaches a client.
#[test]
fn every_word_is_screaming_snake_case() {
  for (_, word) in VOCABULARY {
    assert!(
      word
        .bytes()
        .all(|byte| byte.is_ascii_uppercase() || byte == b'_'),
      "`{word}` is not SCREAMING_SNAKE_CASE"
    );
    assert!(!word.starts_with('_') && !word.ends_with('_'), "`{word}`");
  }
}

/// THE EMITTER'S RESERVED LIST IS THIS VOCABULARY, and this is the one file that can see both.
///
/// `#[ingraph::mutation_error]` refuses a declaration that mints one of these words — a client
/// matching `UNREACHABLE_SOURCE` is asking about a refusal only this framework raises, and an
/// application error wearing it would answer that question wrongly. The list that refusal checks
/// against cannot be read off [`ErrorCode`]: a proc macro's emitter runs before, and without, the
/// crate it generates code for, so `ingraph-codegen` carries the words itself.
///
/// Two lists for one vocabulary is the shape this crate refuses everywhere else, so they are pinned
/// EQUAL here — in the fixture a round that adds a word already has to touch, which is what makes
/// the pin catch that round rather than merely catch a rename.
///
/// It does NOT catch a code minted without joining the walk above; nothing can, `ErrorCode` being
/// `#[non_exhaustive]` and therefore unmatchable exhaustively from anywhere but this crate. What
/// keeps that honest is the fixture's own note — the vocabulary IS the contract — and this assertion
/// is what stops the two halves of it drifting once a word is in.
#[test]
fn the_emitters_reserved_list_is_this_vocabulary() {
  let mut words: Vec<&str> = VOCABULARY.iter().map(|(_, word)| *word).collect();
  words.sort_unstable();
  assert_eq!(
    words,
    ingraph_codegen::error::RESERVED,
    "a word this crate publishes and the macro does not reserve is a word a declaration can steal"
  );
}

/// The extension KEY is one fact, spelled once. A second spelling of it would publish a refusal
/// under a name no client looks in.
#[test]
fn the_extension_key_is_the_one_the_ecosystem_reads() {
  assert_eq!(ErrorCode::EXTENSION, "code");
}

/// THE TRANSPORT's four arms, each under its own word — the mapping the mutation door made
/// reachable, read from the type that owns it.
///
/// The pairing matters as much as the words: the two `UNREACHABLE_*` codes are what a client tells
/// *nothing ran* from *the change was made and not applied* by, and a mapping that folded them would
/// be a wire contract that could not say the second thing at all.
#[test]
fn every_transport_refusal_answers_with_its_own_word() {
  use crate::{QueryError, ToErrorCode as _};

  for (refusal, word) in [
    (QueryError::Unreachable, "UNREACHABLE_NODE"),
    (QueryError::UnreachableSource, "UNREACHABLE_SOURCE"),
    (QueryError::Dropped, "REQUEST_DROPPED"),
    (QueryError::TimedOut, "REQUEST_TIMED_OUT"),
  ] {
    assert_eq!(refusal.error_code().as_str(), word, "{refusal}");
  }
}

/// The two unreachables say WHICH far end is gone, because a client acting on one of them is acting
/// on the effect that did or did not happen.
#[test]
fn the_two_unreachables_name_different_far_ends() {
  use crate::QueryError;

  assert!(
    QueryError::UnreachableSource
      .to_string()
      .contains("control line"),
    "{}",
    QueryError::UnreachableSource
  );
  assert!(
    QueryError::Unreachable.to_string().contains("query node"),
    "{}",
    QueryError::Unreachable
  );
  assert_ne!(
    QueryError::Unreachable.to_string(),
    QueryError::UnreachableSource.to_string()
  );
}

/// Stands in for one emitted `<T>OrderBy`, at the one width this fixture needs: a subject a client
/// can write twice.
#[cfg(feature = "async-graphql")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, async_graphql::OneofObject)]
enum CueOrderBy {
  Title(crate::OrderDirection),
}

#[cfg(feature = "async-graphql")]
impl crate::ToSubjectPath for CueOrderBy {
  fn subject_path(&self) -> crate::SubjectPath {
    const SUBJECT: crate::SubjectPath = crate::SubjectPath::new(&[crate::TermName::new("title")]);
    SUBJECT
  }
}

/// The order decode's refusal answers with the order decode's word — the row that makes
/// [`RepeatedSubject`](crate::RepeatedSubject) a wire refusal rather than a Rust one.
#[cfg(feature = "async-graphql")]
#[test]
fn the_repeated_subject_refusal_answers_with_its_own_word() {
  use async_graphql::InputType;

  use crate::{OrderDirection::Asc, Orderings};

  let written = vec![CueOrderBy::Title(Asc), CueOrderBy::Title(Asc)];
  let refusal = <Orderings<CueOrderBy> as InputType>::parse(Some(InputType::to_value(&written)))
    .expect_err("the second term repeats the first");

  let error = refusal.into_server_error(async_graphql::Pos::default());
  assert_eq!(
    word(error.extensions.as_ref()).as_deref(),
    Some("REPEATED_ORDER_SUBJECT"),
    "the code rides in `extensions`, beside a message nothing matches on"
  );
}

/// The code an error carries, where it carries one.
#[cfg(feature = "async-graphql")]
fn word(extensions: Option<&async_graphql::ErrorExtensionValues>) -> Option<String> {
  match extensions?.get(ErrorCode::EXTENSION)? {
    async_graphql::Value::String(word) => Some(word.clone()),
    _ => None,
  }
}

/// The attachment is the ONE place a code becomes an extension, so a refusal handed to it can never
/// arrive as a message with no word.
#[cfg(feature = "async-graphql")]
#[test]
fn a_refusal_reaches_the_wire_as_a_sentence_and_a_word() {
  struct Refused;

  impl core::fmt::Display for Refused {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
      f.write_str("a sentence for a person")
    }
  }

  impl super::ToErrorCode for Refused {
    fn error_code(&self) -> ErrorCode {
      ErrorCode::RepeatedOrderSubject
    }
  }

  let error = super::refused(&Refused);
  assert_eq!(error.message, "a sentence for a person");
  assert_eq!(
    word(error.extensions.as_ref()).as_deref(),
    Some("REPEATED_ORDER_SUBJECT"),
  );
}