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 wire faces, read the way a client reads them: the names each one publishes, the pair check
//! at the operand's door, and the two shorthand refusals.

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

use crate::{
  Contained, ContainedOperand, ScalarFilter, TimeRange, TimeRangeFilter, TimeRangeOperand,
  TimeRanged, TimeRangedFilter, Timestamp,
};

fn at(second: i64) -> Timestamp {
  Timestamp::from_parts(second, 0).expect("an instant")
}

/// The JSON a client sends for one stretch.
fn sent(start: &str, end: &str) -> Value {
  let mut object = async_graphql::indexmap::IndexMap::new();
  object.insert(async_graphql::Name::new("start"), Value::from(start));
  object.insert(async_graphql::Name::new("end"), Value::from(end));
  Value::Object(object)
}

/// One operand through the door, or the sentence it was refused with.
fn door(value: Value) -> Result<TimeRangeOperand, String> {
  <TimeRangeOperand as InputType>::parse(Some(value))
    .map_err(|refused| refused.into_server_error(Pos::default()).message)
}

/// **THE OPERAND'S TWO SEATS ARE THE INSTANT'S OWN DOOR**, so every spelling that type admits
/// arrives here and no second grammar is written.
#[test]
fn the_seats_are_the_instants_own_grammar() {
  let admitted = door(sent("1970-01-01T00:00:10Z", "1970-01-01T00:00:20Z")).expect("a stretch");
  assert_eq!(admitted.get(), TimeRange::new(at(10), at(20)).unwrap());

  // An OFFSET spelling normalises to the instant it names — the instant's own fold, not this door's.
  let offset = door(sent("1970-01-01T09:00:10+09:00", "1970-01-01T00:00:20Z")).expect("a stretch");
  assert_eq!(offset.get().start(), at(10));

  // A civil datetime is not an instant, and the refusal is the seat's.
  assert!(door(sent("1970-01-01T00:00:10", "1970-01-01T00:00:20Z")).is_err());
}

/// **THE PAIR IS CHECKED AT THE DOOR**, and the sentence a client reads is
/// [`InvertedTimeRange`](crate::InvertedTimeRange)'s own — the rule rather than only the type.
#[test]
fn an_inverted_operand_is_refused_with_the_rule() {
  let refused =
    door(sent("1970-01-01T00:00:20Z", "1970-01-01T00:00:10Z")).expect_err("20 is after 10");

  assert!(
    refused.contains("ends no earlier than it starts"),
    "{refused}"
  );
}

/// **A DEGENERATE OPERAND IS ADMITTED**, which is `mediatime`'s posture reaching the wire: the value
/// is a MARKER, so a client can send one.
#[test]
fn a_degenerate_operand_crosses() {
  let point = door(sent("1970-01-01T00:00:15Z", "1970-01-01T00:00:15Z")).expect("an instant span");
  assert!(point.get().is_instant());
}

/// **THE TWO-SHAPE DOOR TELLS THEM APART BY SYNTAX** — a bare RFC 3339 string is a POSITION, and the
/// bracketed form is a SPAN.
///
/// It is the door that keeps the ruled vocabulary at three words: under half-openness a degenerate
/// span is not a position, so the shape has to be sendable, and it is sendable through the operand
/// rather than through a fourth slot.
#[test]
fn the_contained_door_reads_a_position_or_a_span() {
  fn contained(value: Value) -> Result<Contained, String> {
    <ContainedOperand as InputType>::parse(Some(value))
      .map(|operand| operand.get())
      .map_err(|refused| refused.into_server_error(Pos::default()).message)
  }

  assert_eq!(
    contained(Value::from("1970-01-01T00:00:15Z")).expect("a position"),
    Contained::Instant(at(15))
  );
  assert_eq!(
    contained(Value::from("[1970-01-01T00:00:10Z, 1970-01-01T00:00:20Z)")).expect("a span"),
    Contained::Span(TimeRange::new(at(10), at(20)).unwrap())
  );

  // The SPAN half re-validates: a bracketed text naming an inverted stretch is refused HERE.
  let inverted = contained(Value::from("[1970-01-01T00:00:20Z, 1970-01-01T00:00:10Z)"))
    .expect_err("20 is after 10");
  assert!(
    inverted.contains("ends no earlier than it starts"),
    "{inverted}"
  );

  // A bracketed text that is not a stretch is refused AS A STRETCH rather than retried as a
  // position, so the error names the shape the client actually wrote.
  let endpoints = contained(Value::from("[nonsense, more)")).expect_err("not a stretch");
  assert!(endpoints.contains("not an instant"), "{endpoints}");
  let notation = contained(Value::from("[nonsense)")).expect_err("no comma, no stretch");
  assert!(notation.contains("half-open reading"), "{notation}");

  // STRICT OUT: each shape is written back in its own exact form, so what a client reads it can send.
  assert_eq!(
    InputType::to_value(&ContainedOperand::new(Contained::Instant(at(15)))),
    Value::from("1970-01-01T00:00:15Z")
  );
  assert_eq!(
    InputType::to_value(&ContainedOperand::new(Contained::Span(
      TimeRange::new(at(10), at(20)).unwrap()
    ))),
    Value::from("[1970-01-01T00:00:10Z, 1970-01-01T00:00:20Z)")
  );

  assert!(
    contained(Value::from(15)).is_err(),
    "a number is not a shape"
  );
}

/// **BOTH SEATS ARE REQUIRED**, and an object missing one is refused by that seat rather than by a
/// sentence of this door's.
#[test]
fn a_missing_seat_is_refused() {
  let mut half = async_graphql::indexmap::IndexMap::new();
  half.insert(
    async_graphql::Name::new("start"),
    Value::from("1970-01-01T00:00:10Z"),
  );

  assert!(door(Value::Object(half)).is_err());
  assert!(door(Value::Null).is_err());
  assert!(
    door(Value::from("1970-01-01T00:00:10Z")).is_err(),
    "a range has two seats and neither is the obvious one, so there is no bare form"
  );
}

/// **STRICT OUT** — the operand renders as the same two keys it takes, so a value read back and sent
/// again is the same value by the shortest route.
#[test]
fn the_operand_renders_the_two_seats_it_takes() {
  let operand = TimeRangeOperand::new(TimeRange::new(at(10), at(20)).unwrap());
  let rendered = InputType::to_value(&operand);

  assert_eq!(door(rendered).expect("its own form").get(), operand.get());
}

/// **NO SHORTHAND AT THE RANGE FILTER**, and the refusal NAMES the three words a client could have
/// meant rather than only the type it expected.
#[test]
fn a_bare_value_at_the_range_filter_is_a_named_refusal() {
  let bare = <TimeRangeFilter as InputType>::parse(Some(Value::from("1970-01-01T00:00:10Z")))
    .expect_err("a bare value does not say which word was meant");
  let message = bare.into_server_error(Pos::default()).message;

  assert!(message.contains("overlaps"), "{message}");
  assert!(message.contains("contains"), "{message}");
  assert!(message.contains("within"), "{message}");
}

/// **`{ start: …, end: … }` AT THE FILTER IS THE TWO COMPONENT FILTERS**, not an interval word — and
/// the shape is worth pinning precisely because it LOOKS like an operand.
///
/// The two keys are this face's own `start` and `end` slots, each a `TimestampFilter`, and each of
/// those reads a bare value as its `eq` under the shorthand law. So the object means *starts exactly
/// here and ends exactly there*, which is a legitimate question and is not any of the three interval
/// words. A client that meant *meets this window* writes `overlaps` and gets a
/// [`TimeRangeOperand`] slot, which is the whole point of the words being named.
#[test]
fn the_two_component_keys_are_not_an_interval_operand() {
  let filter = <TimeRangeFilter as InputType>::parse(Some(sent(
    "1970-01-01T00:00:10Z",
    "1970-01-01T00:00:20Z",
  )))
  .expect("the two component slots, each taking its own shorthand");

  assert!(filter.overlaps().is_none());
  assert_eq!(filter.start().and_then(ScalarFilter::eq), Some(&at(10)));
  assert_eq!(filter.end().and_then(ScalarFilter::eq), Some(&at(20)));
}

/// **THE FIVE SLOTS ARE ALL OPTIONAL AND ALL LONGHAND**, and the empty object asks nothing.
#[test]
fn the_range_filter_takes_its_five_slots() {
  let mut object = async_graphql::indexmap::IndexMap::new();
  object.insert(
    async_graphql::Name::new("overlaps"),
    sent("1970-01-01T00:00:10Z", "1970-01-01T00:00:20Z"),
  );

  let filter = <TimeRangeFilter as InputType>::parse(Some(Value::Object(object)))
    .expect("one named interval word");

  assert_eq!(
    filter.overlaps().map(TimeRangeOperand::get),
    Some(TimeRange::new(at(10), at(20)).unwrap())
  );
  assert!(filter.contains().is_none());

  let empty = <TimeRangeFilter as InputType>::parse(Some(Value::Object(Default::default())))
    .expect("an empty object");
  assert!(empty.is_empty());
}

/// **A ROUND TRIP THROUGH THE FILTER'S OWN RENDERING**, which is what keeps the field list one list:
/// `to_value` writes the names `parse` reads.
#[test]
fn the_range_filter_round_trips_its_own_rendering() {
  let filter = TimeRangeFilter::new()
    .with_within(TimeRange::new(at(0), at(100)).unwrap())
    .with_start(ScalarFilter::new().with_gte(at(5)));

  let rendered = InputType::to_value(&filter);
  let read = <TimeRangeFilter as InputType>::parse(Some(rendered)).expect("its own form");

  assert_eq!(read, filter);
}

/// **NO SHORTHAND AT THE TIMED FILTER EITHER**, and the sentence names the two halves.
#[test]
fn a_bare_value_at_the_timed_filter_is_a_named_refusal() {
  let bare = <TimeRangedFilter<ScalarFilter<i64>> as InputType>::parse(Some(Value::from(7)))
    .expect_err("a bare value does not say which half");
  let message = bare.into_server_error(Pos::default()).message;

  assert!(message.contains("range"), "{message}");
  assert!(message.contains("data"), "{message}");
}

/// **THE TIMED FILTER'S TWO SLOTS**, and its round trip.
#[test]
fn the_timed_filter_takes_a_stretch_and_a_payload() {
  let filter = TimeRangedFilter::new()
    .with_range(TimeRangeFilter::new().with_overlaps(TimeRange::new(at(10), at(20)).unwrap()))
    .with_data(ScalarFilter::<i64>::new().with_eq(7i64));

  let rendered = InputType::to_value(&filter);
  let read = <TimeRangedFilter<ScalarFilter<i64>> as InputType>::parse(Some(rendered))
    .expect("its own form");

  assert_eq!(read, filter);
  assert!(!read.is_empty());
  assert!(TimeRangedFilter::<ScalarFilter<i64>>::new().is_empty());
}

/// **THE NAMES**, which are the whole of what a generic face publishes to a client.
///
/// The output object is `TimeRanged` before the PAYLOAD's own object name and the filter is
/// `TimeRanged` before the PAYLOAD FILTER's own input name, so the two sit beside each other without
/// either colliding with the other.
#[test]
fn the_published_names_are_composed_from_the_parameter() {
  assert_eq!(<TimeRange as OutputType>::type_name(), "TimeRange");
  assert_eq!(
    <TimeRangeOperand as InputType>::type_name(),
    "TimeRangeOperand"
  );
  assert_eq!(
    <TimeRangeFilter as InputType>::type_name(),
    "TimeRangeFilter"
  );

  assert_eq!(
    <TimeRanged<Timestamp> as OutputType>::type_name(),
    "TimeRangedTimestamp"
  );
  assert_eq!(
    <TimeRangedFilter<ScalarFilter<Timestamp>> as InputType>::type_name(),
    "TimeRangedTimestampFilter"
  );
  assert_eq!(
    <TimeRangedFilter<ScalarFilter<i64>> as InputType>::type_name(),
    "TimeRangedI64Filter"
  );
}

/// **THE SDL, RENDERED FROM A REAL SCHEMA** — which is the half a `type_name()` cannot show.
///
/// A name is answered without a registry ever being touched, so a broken `create_type_info` passes
/// every assertion above. This builds a schema whose one field RETURNS a timed instant and takes a
/// timed filter, and reads what a client would read: five blocks, the field lists in declaration
/// order, and the two composed names sitting beside each other.
#[test]
fn the_schema_publishes_both_citizens() {
  struct Query;

  #[async_graphql::Object]
  impl Query {
    async fn heard(
      &self,
      _asked: TimeRangedFilter<ScalarFilter<Timestamp>>,
    ) -> TimeRanged<Timestamp> {
      TimeRanged::new(TimeRange::instant(at(0)), at(0))
    }

    /// A bare stretch beside it, so the OBJECT and its OPERAND are both reachable — the operand
    /// arrives through the filter above and the object through this field.
    async fn trim(&self, _asked: TimeRangeFilter) -> TimeRange {
      TimeRange::instant(at(0))
    }
  }

  /// The SDL with its DESCRIPTIONS stripped, which is what puts the five blocks below on one
  /// footing: async-graphql publishes a Rust doc comment as a type's or a field's description, so an
  /// OBJECT's rendering carries the prose written above it and the two hand-written INPUT faces —
  /// which set `description: None` — carry none. What this page is about is the SHAPE, and a doc
  /// edit is not a schema change.
  fn shape(sdl: &str) -> String {
    let mut stripped = String::new();
    let mut inside = false;

    for line in sdl.lines() {
      let trimmed = line.trim();
      // `"""` alone opens or closes a block; `"""…"""` is a whole description on one line.
      if trimmed.starts_with("\"\"\"") {
        if trimmed == "\"\"\"" {
          inside = !inside;
        }
        continue;
      }
      if inside {
        continue;
      }
      stripped.push_str(line);
      stripped.push('\n');
    }

    stripped
  }

  let sdl = shape(
    &async_graphql::Schema::new(
      Query,
      async_graphql::EmptyMutation,
      async_graphql::EmptySubscription,
    )
    .sdl(),
  );

  for block in [
    "type TimeRange {\n\tstart: Timestamp!\n\tend: Timestamp!\n}",
    "input TimeRangeOperand {\n\tstart: Timestamp!\n\tend: Timestamp!\n}",
    "input TimeRangeFilter {\n\toverlaps: TimeRangeOperand\n\tcontains: ContainedOperand\n\twithin: \
     TimeRangeOperand\n\tstart: TimestampFilter\n\tend: TimestampFilter\n}",
    "scalar ContainedOperand",
    "type TimeRangedTimestamp {\n\trange: TimeRange!\n\tdata: Timestamp!\n}",
    "input TimeRangedTimestampFilter {\n\trange: TimeRangeFilter\n\tdata: TimestampFilter\n}",
  ] {
    assert!(
      sdl.contains(block),
      "missing from the SDL:\n{block}\n\n{sdl}"
    );
  }
}

/// **THE NULLABLE TWIN EXISTS FOR BOTH FACES**, which is the row a `NOT NULL` column does not need
/// and an optional one cannot do without.
#[test]
fn a_nullable_column_gets_the_twin() {
  use crate::Nullable;

  assert_eq!(
    <Nullable<TimeRangeFilter> as InputType>::type_name(),
    "NullableTimeRangeFilter"
  );
  assert_eq!(
    <Nullable<TimeRangedFilter<ScalarFilter<i64>>> as InputType>::type_name(),
    "NullableTimeRangedI64Filter"
  );
}