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 SEAM's own assertions, taken with no engine, no wire and no store — which is the whole
//! claim the neutrality makes: everything here compiles and runs in a build that has never heard of
//! async-graphql.

use std::sync::Arc;

use super::{BatchAnswer, BatchDoor, BatchError, Batched};
use crate::graphql::{ErrorCode, ToErrorCode};

/// A refusal that names its own word, standing in for the engine's.
#[derive(Debug)]
struct Refused;

impl core::fmt::Display for Refused {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.write_str("this query did not run: the pool is closed")
  }
}

impl core::error::Error for Refused {}

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

/// A refusal with NO word of its own — the third-party loader's case.
#[derive(Debug)]
struct Wordless;

impl core::fmt::Display for Wordless {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.write_str("the remote index timed out")
  }
}

impl core::error::Error for Wordless {}

/// A provider that answers from a fixed table, and remembers how many asks reached it.
///
/// A hand-written [`Batched`] rather than an engine, which is the point: the door's openness is
/// exercised by the shape an application would write, and this file needs no `dataloader` feature
/// to run.
#[derive(Debug, Default)]
struct Table {
  refuse: bool,
}

impl Batched<i64, &'static str> for Table {
  fn one(&self, key: i64) -> BatchAnswer<'_, &'static str> {
    let refuse = self.refuse;
    Box::pin(async move {
      if refuse {
        return Err(BatchError::new(Refused));
      }
      Ok(match key {
        1 => Some("clapper"),
        2 => Some("gate"),
        _ => None,
      })
    })
  }
}

/// **THE WORD TRAVELS** — a refusal that names its own code keeps it, so the batched lane crosses
/// under the same word the per-row lane would.
#[test]
fn a_refusal_that_names_its_word_keeps_it() {
  let error = BatchError::new(Refused);
  assert_eq!(error.code(), ErrorCode::StoreRefused);
  assert_eq!(error.error_code(), ErrorCode::StoreRefused);
}

/// **THE FRAMEWORK WORDS THE WORDLESS** — a loader whose failure implements no [`ToErrorCode`] is
/// still crossable, because whoever built the [`BatchError`] chose the word.
#[test]
fn a_refusal_without_a_word_is_given_one() {
  let error = BatchError::coded(ErrorCode::StoreRefused, Wordless);
  assert_eq!(error.code(), ErrorCode::StoreRefused);
  assert_eq!(error.to_string(), "the remote index timed out");
}

/// **THE SENTENCE IS THE REFUSAL'S** — no wrapper prose in front of it, so a client reads what the
/// store said and not what a layer called itself.
#[test]
fn the_sentence_is_the_refusals_own() {
  let error = BatchError::new(Refused);
  assert_eq!(error.to_string(), Refused.to_string());
}

/// **THE SOURCE CHAIN REACHES THROUGH** — a caller that walks it finds the refusal itself.
#[test]
fn the_carried_refusal_is_the_source() {
  let error = BatchError::new(Refused);
  let source = core::error::Error::source(&error).expect("the refusal");
  assert_eq!(source.to_string(), Refused.to_string());
  assert_eq!(error.refusal().to_string(), Refused.to_string());
}

/// **CLONE IS THE FAN-OUT'S REQUIREMENT, AND IT IS A REFCOUNT** — one batch failure reaches every
/// asker that shared it, and cloning it copies no sentence.
#[test]
fn a_refusal_clones_to_every_asker() {
  let error = BatchError::new(Refused);
  let fanned = error.clone();
  assert_eq!(fanned.code(), error.code());
  assert_eq!(fanned.to_string(), error.to_string());
  assert!(
    core::ptr::eq(
      core::ptr::from_ref(error.refusal()).cast::<()>(),
      core::ptr::from_ref(fanned.refusal()).cast::<()>(),
    ),
    "the clone shares the refusal rather than copying it"
  );
}

/// **A DOOR ANSWERS THROUGH WHATEVER IS BEHIND IT** — the hit, and the miss as `Ok(None)`.
#[tokio::test]
async fn a_door_answers_hits_and_misses() {
  let door: BatchDoor<i64, &'static str> = BatchDoor::new(Arc::new(Table::default()));

  assert_eq!(door.one(1).await.expect("an answer"), Some("clapper"));
  assert_eq!(door.one(2).await.expect("an answer"), Some("gate"));
  assert_eq!(
    door.one(9).await.expect("an answer"),
    None,
    "a miss is Ok(None), which is the per-row lane's answer too"
  );
}

/// **A DOOR'S REFUSAL IS THE PROVIDER'S** — carried out whole, word included.
#[tokio::test]
async fn a_door_carries_its_providers_refusal() {
  let door: BatchDoor<i64, &'static str> = BatchDoor::new(Arc::new(Table { refuse: true }));
  let refusal = door.one(1).await.expect_err("a refusal");
  assert_eq!(refusal.code(), ErrorCode::StoreRefused);
}

/// **A DOOR IS CLONEABLE WITHOUT ITS PARAMETERS BEING** — the hand-written impls' whole reason.
///
/// `&'static str` is [`Clone`] and `i64` is, so the ASSERTION here is about the bound rather than
/// the values: the type checks because the impl states none, which a derive would not have allowed
/// to be true of a non-`Clone` value type. The compile IS the test.
#[test]
fn a_door_clones_by_refcount() {
  let door: BatchDoor<i64, &'static str> = BatchDoor::new(Arc::new(Table::default()));
  let twin = door.clone();
  assert!(format!("{twin:?}").contains("BatchDoor"));
}

/// **THE DEBUG LINE NAMES WHICH DOOR IT IS** — the two halves of *which record, in which database*.
#[test]
fn a_doors_debug_names_its_two_types() {
  let door: BatchDoor<i64, &'static str> = BatchDoor::new(Arc::new(Table::default()));
  let rendered = format!("{door:?}");
  assert!(rendered.contains("i64"), "{rendered}");
  assert!(rendered.contains("str"), "{rendered}");
}