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
//! What the query layer refuses, and what its refusals say.

use super::{SqlQueryError, offset};
use crate::{
  CursorError, OrderMismatch, OrderSignature,
  comparison::sql::{BindCeilingError, SqlLoweringError},
};

/// A `skip` past what an `OFFSET` binds REFUSES, and it neither panics nor saturates.
///
/// Both alternatives were shipped somewhere and both are wrong. polarsync narrowed the same number
/// with `i64::try_from(…).unwrap()`, so a client's oversized offset took the process down; and a
/// value clamped to the ceiling would answer a different question with nothing to say it had.
#[test]
fn a_skip_past_the_binding_width_refuses_rather_than_wrapping() {
  let ceiling = i64::MAX as u64;
  assert_eq!(offset(0).unwrap(), 0);
  assert_eq!(offset(ceiling).unwrap(), ceiling);

  let refused = offset(ceiling + 1).expect_err("one past the width is not bindable");
  assert!(
    matches!(refused, SqlQueryError::Skip(skip) if skip == ceiling + 1),
    "the refusal carries what was asked for: {refused:?}"
  );
  assert!(offset(u64::MAX).is_err());
}

/// Every refusal names its own subject, and the ones that wrap another error carry it as a
/// `source` — so a caller reading a chain sees the dialect's own sentence rather than this layer's
/// paraphrase of it.
#[test]
fn a_refusal_carries_the_error_it_wraps() {
  let lowering = SqlQueryError::Lowering(SqlLoweringError::BindCeiling(BindCeilingError::new(
    40_000, 2, 32_766,
  )));
  assert!(core::error::Error::source(&lowering).is_some());
  assert!(lowering.to_string().contains("does not lower here"));

  let cursor = SqlQueryError::Cursor(CursorError::Order(OrderMismatch::new(
    OrderSignature::of(&[]),
    OrderSignature::of(&[]),
  )));
  assert!(core::error::Error::source(&cursor).is_some());
  assert!(cursor.to_string().contains("cannot resume there"));

  let skip = SqlQueryError::Skip(u64::MAX);
  assert!(
    core::error::Error::source(&skip).is_none(),
    "a ceiling is this layer's own and wraps nothing"
  );
  assert!(skip.to_string().contains("past the"));
}

/// **The seven wire words**, walked as a table so no arm is left without one and none of them
/// silently changes: the vocabulary is a client's contract, and the mapping is where an arm joins
/// it.
///
/// Every value here is a REAL refusal rather than a placeholder — `PagingOrderError` is built by
/// running the frame against a backend that keeps collections in a table of its own, which is the
/// path `Paging::fetch` takes to raise one.
#[test]
fn each_arm_answers_with_the_word_the_vocabulary_ratified() {
  use crate::{
    ErrorCode, FieldName, OrderDirection, OrderTerm, TermName, ToErrorCode,
    comparison::sql::SqlOrderError,
    query::{
      CollectionBoundary, CollectionOrdering, NullPlacement, OrderCapability, ShadowBoundary,
      ShadowOrdering, TermRepetition, partition,
    },
  };

  /// A backend that keeps a collection in a table of its own — SQLite's and MySQL's answer, and the
  /// shape that makes a collection term a page's remainder.
  struct EdgeStored;

  impl OrderCapability for EdgeStored {
    const NULLS: NullPlacement = NullPlacement::Reachable;
    const REPEATED_TERMS: TermRepetition = TermRepetition::Admitted;
    const COLLECTIONS: CollectionOrdering = CollectionOrdering::Divergent;
    const COLLECTION_BOUNDARY: CollectionBoundary = CollectionBoundary::Unbindable;
    const SHADOWS: ShadowOrdering = ShadowOrdering::Bytewise;
    const SHADOW_BOUNDARY: ShadowBoundary = ShadowBoundary::Bindable;
  }

  let terms = [OrderTerm::edge(
    TermName::new("tags"),
    FieldName::new("tags"),
    OrderDirection::Asc,
  )];
  let paging = partition::<EdgeStored>(&terms)
    .paging::<EdgeStored>()
    .expect_err("an edge-stored collection is not a page's order");

  let rows: [(SqlQueryError, ErrorCode); 7] = [
    (
      SqlQueryError::Sql(sqlx::Error::PoolClosed),
      ErrorCode::StoreRefused,
    ),
    (
      SqlQueryError::Lowering(SqlLoweringError::BindCeiling(BindCeilingError::new(
        40_000, 2, 32_766,
      ))),
      ErrorCode::UnsupportedFilter,
    ),
    (
      SqlQueryError::Order(SqlOrderError::Empty),
      ErrorCode::UnrenderableOrder,
    ),
    (SqlQueryError::PageOrder(paging), ErrorCode::UnpageableOrder),
    (
      SqlQueryError::Cursor(CursorError::Order(OrderMismatch::new(
        OrderSignature::of(&[]),
        OrderSignature::of(&[]),
      ))),
      ErrorCode::UnusableCursor,
    ),
    (
      SqlQueryError::Crossing("a stored row is not this record".into()),
      ErrorCode::UnreadableRow,
    ),
    (SqlQueryError::Skip(u64::MAX), ErrorCode::OversizedSkip),
  ];

  for (refusal, code) in &rows {
    assert_eq!(refusal.error_code(), *code, "{refusal}");
  }

  // No two arms share a word, which is what makes the mapping worth matching on: a client reading
  // `UNPAGEABLE_ORDER` knows the order rendered and the cursor could not take a boundary in it, and
  // that is a different fix from `UNRENDERABLE_ORDER`'s.
  let mut words: Vec<&str> = rows.iter().map(|(_, code)| code.as_str()).collect();
  let written = words.len();
  words.sort_unstable();
  words.dedup();
  assert_eq!(words.len(), written, "each arm has a word of its own");
}

/// …and the word REACHES A CLIENT, read out of `extensions.code` on a live response — which is the
/// half a mapping test cannot show. The engine's refusals had no code at all before this round.
#[cfg(feature = "async-graphql")]
#[test]
fn an_engine_refusal_reaches_the_wire_as_a_sentence_and_a_word() {
  use core::{
    future::Future,
    pin::pin,
    task::{Context as TaskContext, Poll, Waker},
  };

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

  use crate::ErrorCode;

  struct Query;

  /// The resolver shape the emission will write: the engine's refusal handed to `refused`, never an
  /// error the resolver assembles itself.
  ///
  /// The oversized skip is the RESOLVER's rather than an argument, because the ceiling is past what
  /// async-graphql's `Int` carries — a client cannot spell `i64::MAX + 1` in a document at all, and
  /// a document that tried would be refused by the VALIDATOR before any resolver ran. What is under
  /// test is the crossing from a typed engine refusal to `extensions.code`, and that crossing is the
  /// same whichever party produced the number.
  #[Object]
  impl Query {
    async fn cues(&self) -> async_graphql::Result<u64> {
      super::offset(u64::MAX).map_err(|refusal| crate::refused(&refusal))
    }
  }

  let schema = Schema::build(Query, EmptyMutation, EmptySubscription).finish();
  let response = {
    let mut request = pin!(schema.execute("{ cues }"));
    let mut cx = TaskContext::from_waker(Waker::noop());
    loop {
      if let Poll::Ready(response) = request.as_mut().poll(&mut cx) {
        break response;
      }
    }
  };

  let error = response.errors.first().expect("this skip is refused");
  assert!(error.message.contains("is past the"), "{}", error.message);
  let code = error
    .extensions
    .as_ref()
    .and_then(|extensions| extensions.get(ErrorCode::EXTENSION));
  assert_eq!(
    code,
    Some(&Value::String(String::from("OVERSIZED_SKIP"))),
    "the code rides in `extensions`, beside a message nothing matches on"
  );
}