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 names both faces publish, the order their fields arrive in, and the shorthand neither takes.

use async_graphql::{InputType, OutputType, Value};

use crate::{NormCoord, ScalarFilter};

type F32Filter = ScalarFilter<f32>;

use super::{
  super::tests::located, Detection, DetectionFilter, LocatedDetection, LocatedDetectionFilter,
};

/// **ONE NAME IS COMPOSED AND ONE IS NOT** — the concrete type publishes its own name, and the
/// generic one composes the component's onto it because GraphQL keeps ONE FLAT NAMESPACE.
#[test]
fn the_published_names_compose_only_where_a_parameter_varies() {
  assert_eq!(<Detection as OutputType>::type_name(), "Detection");
  assert_eq!(
    <DetectionFilter as InputType>::type_name(),
    "DetectionFilter"
  );

  assert_eq!(
    <LocatedDetection<NormCoord> as OutputType>::type_name(),
    "LocatedDetectionF32",
    "a coordinate has no scalar of its own, so the name composed from its published form is the \
     WIDTH's — RAISED, a Rust width not being a name. The geometry house publishes \
     `BoundingBoxF32` through the same expression."
  );
  assert_eq!(
    <LocatedDetection<f64> as OutputType>::type_name(),
    "LocatedDetectionF64"
  );
  assert_eq!(
    <LocatedDetectionFilter<F32Filter> as InputType>::type_name(),
    "LocatedDetectionF32Filter",
    "the OUTPUT name composes from the component and the INPUT name from the component FILTER, so \
     the two sit beside each other without colliding"
  );
}

/// **THE TWO HALVES NOW AGREE, letter for letter** — which is the whole of what the raise bought and
/// the one claim the assertions above cannot make separately.
///
/// An output name and its filter's are built from two different sources — a component's published
/// SCALAR and a component FILTER's name — and those sources disagree about case by construction. So
/// the property worth pinning is not either name but their RELATION: strip the filter's suffix and
/// what is left is the object's name exactly. A raise applied to one half and not the other passes
/// every assertion above and fails this one.
#[test]
fn the_object_name_is_its_filters_name_without_the_suffix() {
  let object = <LocatedDetection<NormCoord> as OutputType>::type_name();
  let filter = <LocatedDetectionFilter<F32Filter> as InputType>::type_name();

  assert_eq!(
    filter.strip_suffix("Filter"),
    Some(object.as_ref()),
    "the two composed names differ only by the suffix a filter wears"
  );
}

/// **THE CLASSIFICATION IS FLATTENED ON THE WIRE**, and the located face's field list is the
/// detection face's plus one — built by CALLING it, so a facet added tomorrow arrives at both.
#[test]
fn the_located_face_publishes_the_classifications_fields_beside_its_own() {
  let mut registry = async_graphql::registry::Registry::default();

  let detection: Vec<String> = super::detection_fields(&mut registry)
    .keys()
    .cloned()
    .collect();
  assert_eq!(detection, ["label", "confidence"]);

  let located: Vec<String> = super::located_fields::<F32Filter>(&mut registry)
    .keys()
    .cloned()
    .collect();
  assert_eq!(located, ["label", "confidence", "bbox"]);
}

/// The RENDER agrees with the registration, name for name and in order.
#[test]
fn the_render_is_the_same_three_names_in_the_same_order() {
  let filter = LocatedDetectionFilter::<F32Filter>::new();
  let rendered: Vec<String> = super::located_values(&filter)
    .keys()
    .map(|name| String::from(name.as_str()))
    .collect();

  assert_eq!(rendered, ["label", "confidence", "bbox"]);
}

/// **NO SHORTHAND at either face** — a bare value does not say which facet it is asking about, and
/// there is no whole-detection operator for it to be.
#[test]
fn a_bare_value_is_refused_by_name() {
  let refused = <DetectionFilter as InputType>::parse(Some(Value::String("cat".into())))
    .expect_err("a bare value has no whole-value slot to land in");
  assert!(said(refused).contains("asks about FACETS"));

  let refused =
    <LocatedDetectionFilter<F32Filter> as InputType>::parse(Some(Value::Number(1.into())))
      .expect_err("a bare value has no whole-value slot to land in");
  assert!(said(refused).contains("asks about FACETS"));
}

/// The longhand round-trips: an object with no keys is the empty filter, which asks nothing.
#[test]
fn an_empty_object_is_the_empty_filter() {
  let parsed = <DetectionFilter as InputType>::parse(Some(Value::Object(Default::default())))
    .expect("an object with no facets set is a filter that asks nothing");

  assert!(parsed.is_empty());

  let parsed = <LocatedDetectionFilter<F32Filter> as InputType>::parse(Some(Value::Object(
    Default::default(),
  )))
  .expect("an object with no facets set is a filter that asks nothing");

  assert!(parsed.is_empty());
}

/// **The crossing OUT is a BORROW**, at both arities — the `#[Object]` resolves it, so a face hands
/// back what the row already holds.
#[test]
fn both_composites_cross_out_by_borrow() {
  use crate::ToGraphqlOutput;

  let subject = located();
  let borrowed: &LocatedDetection<NormCoord> =
    <LocatedDetection<NormCoord> as ToGraphqlOutput>::to_graphql_output(&subject);
  assert!(core::ptr::eq(borrowed, &subject));

  let classification = subject.detection();
  let borrowed: &Detection = <Detection as ToGraphqlOutput>::to_graphql_output(classification);
  assert!(core::ptr::eq(borrowed, classification));
}

/// The sentence a refusal carries, reached the one way async-graphql publishes it: an
/// `InputValueError` states no `Display` of its own until it is placed in a document.
fn said<T: InputType>(refused: async_graphql::InputValueError<T>) -> String {
  refused
    .into_server_error(async_graphql::Pos::default())
    .message
}

/// **THE TRIO'S COMPOSED NAMES**, on the located form's own terms — and the SYMBOLOGY scalar beside
/// them, which is the one name in this house that composes from nothing.
///
/// The three payload citizens are generic over the geometry component exactly as the located form
/// is, so a schema holding a normalized reading and a metric one carries two names. The symbology is
/// concrete and open, so it publishes ONE scalar: `Symbology`.
#[test]
fn the_payload_trios_names_compose_where_a_parameter_varies_and_the_scalar_does_not() {
  assert_eq!(
    <super::TextDetection<NormCoord> as OutputType>::type_name(),
    "TextDetectionF32"
  );
  assert_eq!(
    <super::BarcodeDetection<NormCoord> as OutputType>::type_name(),
    "BarcodeDetectionF32"
  );
  assert_eq!(
    <super::DocumentSegment<NormCoord> as OutputType>::type_name(),
    "DocumentSegmentF32"
  );
  assert_eq!(
    <super::DocumentSegment<f64> as OutputType>::type_name(),
    "DocumentSegmentF64",
    "a second instantiation is a second name, which is what one flat namespace demands"
  );

  assert_eq!(
    <super::Symbology as InputType>::type_name(),
    "Symbology",
    "the vocabulary is one scalar at every seat that holds it"
  );

  for (object, filter) in [
    (
      <super::TextDetection<NormCoord> as OutputType>::type_name(),
      <super::TextDetectionFilter<F32Filter> as InputType>::type_name(),
    ),
    (
      <super::BarcodeDetection<NormCoord> as OutputType>::type_name(),
      <super::BarcodeDetectionFilter<F32Filter> as InputType>::type_name(),
    ),
    (
      <super::DocumentSegment<NormCoord> as OutputType>::type_name(),
      <super::DocumentSegmentFilter<F32Filter> as InputType>::type_name(),
    ),
  ] {
    assert_eq!(
      filter.strip_suffix("Filter"),
      Some(object.as_ref()),
      "the two composed names differ only by the suffix a filter wears"
    );
  }
}

/// **THE SYMBOLOGY SCALAR IS WIDE IN AND STRICT OUT**, and its only refusal is the JSON kind.
#[test]
fn the_symbology_scalar_reads_every_spelling_and_writes_the_canonical_one() {
  use async_graphql::{ScalarType, Value};

  assert_eq!(
    <super::Symbology as ScalarType>::parse(Value::String(String::from("DATA-MATRIX")))
      .expect("a string is a symbology"),
    super::Symbology::DataMatrix
  );
  assert_eq!(
    ScalarType::to_value(&super::Symbology::DataMatrix),
    Value::String(String::from("data_matrix")),
    "…and it comes back canonical, whichever spelling arrived"
  );

  assert_eq!(
    <super::Symbology as ScalarType>::parse(Value::String(String::from("han xin")))
      .expect("an open vocabulary refuses no spelling")
      .as_str(),
    "hanxin"
  );

  assert!(<super::Symbology as ScalarType>::parse(Value::Number(1.into())).is_err());
  assert!(!<super::Symbology as ScalarType>::is_valid(&Value::Number(
    1.into()
  )));
  assert!(<super::Symbology as ScalarType>::is_valid(&Value::String(
    String::from("qr")
  )));
}

/// **THE BARCODE FACE'S TWO TEXT-SHAPED FACETS PART COMPANY ON THE WIRE**, which is the whole
/// sentence its filter makes: the payload takes the affix family and the symbology takes membership.
#[test]
fn the_barcode_filter_parses_its_payload_as_text_and_its_symbology_as_a_vocabulary() {
  use async_graphql::value;

  type Face = super::BarcodeDetectionFilter<F32Filter>;

  let sent = value!({
    "payload": { "contains": "https://" },
    "symbology": { "in": ["qr", "MICRO-QR"] },
    "bbox": { "area": { "gte": 0.01 } },
  });
  let parsed = <Face as InputType>::parse(Some(sent)).expect("every facet is the face's own");

  assert_eq!(
    parsed.payload().and_then(crate::TextFilter::contains),
    Some(&smol_bytes::Utf8Bytes::from("https://")),
    "a payload is FREE TEXT, so the substring question is the one people ask"
  );
  assert_eq!(
    parsed.symbology().and_then(crate::EnumFilter::in_),
    Some(&[super::Symbology::Qr, super::Symbology::MicroQr][..]),
    "…and a standard is a VOCABULARY, so membership is the whole question — folded at the door"
  );
  assert!(
    parsed.bbox().is_some(),
    "the geometry facet arrives whole, area facet and all"
  );
}