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 order a client writes, and the door it comes in through.
//!
//! The wire face is a LIST — `[<T>OrderBy!]` — because sequence IS the semantics and GraphQL has no
//! map type. What the list decodes INTO is a map keyed by the SUBJECT each term names, so the one
//! thing a list can spell that an order cannot hold — the same subject named twice — is refused at
//! the parse rather than carried down to a backend.
//!
//! # Why a repeat is refused and not quietly dropped
//!
//! A second term over a subject an earlier term already ordered by can reorder nothing: inside the
//! first term's tie group that column is CONSTANT, whichever direction the second one runs in. So a
//! repeat is not a different order — it is the same order with a term that means nothing — and the
//! backends do not agree about what that nothing costs. SQL carries it harmlessly and pays for it
//! once per row; a MongoDB sort is a BSON document whose keys are unique, so there the second term
//! REPLACES the first and the order silently runs the other way. Refusing is the only answer that
//! reads the same at every backend, and refusing at the DOOR is what keeps that divergence out of
//! wire semantics rather than merely out of one lowering.
//!
//! A caller's own list is the only place a repeat can come from. The framework's own default cannot
//! collide with a client's term either, and that is `complete`'s doing: it MOVES the key rather than
//! repeating it where a client's order already named it — so a client that orders by the key is
//! writing a legal order, not a repeat.
//!
//! # An EMPTY list is an order, an ABSENT argument is the same order, and the key is what both mean
//!
//! `[]` decodes to the empty order, and an absent `orderBy` normalises to it — [`Orderings::default`]
//! is that one door. What either becomes is decided one layer up by the emitted
//! `<T>OrderBy::complete`, which appends the record's KEY ASCENDING to any order that did not name
//! it: so both spell *the key, ascending*, which is unique and therefore a TOTAL order, and a page
//! over it neither skips nor repeats a row.
//!
//! The two were once different queries — `None` a client that never wrote an order and was refused a
//! page, `Some([])` one that asked for the address order — and the key default collapsed them.
//! Refusing the absent case bought a client nothing: it had to write `[]` to get exactly the order
//! the refusal was telling it about.
//!
//! What still has no default is the ENGINE's unordered lane, and that is a different question rather
//! than the same one answered twice. A Rust query that never calls `.order(…)` gets no `ORDER BY` at
//! all — SQL's own unordered semantics, and a sort nobody asked for is work every row pays for — and
//! a page there is a missing method rather than a defaulted order. The wire has no such lane: every
//! list field it serves is one a client may page.
//!
//! # The wrapper is not a schema name
//!
//! [`Orderings`] renders as the ARRAY and never as a type of its own: its `type_name` is
//! `[<T>OrderBy!]`, which is exactly what a `Vec` of the same term renders as, so the decode is
//! invisible to a client and a schema review sees the list the design ruled. A named wrapper input
//! would have been a second thing for a client to learn about an order that has not changed.

#[cfg(feature = "async-graphql")]
use indexmap::IndexMap;

use crate::TermName;

/// The SUBJECT one ordering term names: the path to a column, root-first, under the names no
/// per-database rename can move.
///
/// # A PATH, because a subject is not always one segment
///
/// `cover.title` and `title` are two subjects, and one order may name both. What makes them two is
/// the WHOLE path rather than its head — `cover.title` and `cover.duration` are two as well — so a
/// uniqueness test comparing first segments would refuse orders that are perfectly well formed.
/// Today every emitted term is one segment, and holding the path is what keeps the day a term
/// reaches through a relation from being a change to this rule.
///
/// # The segments are [`TermName`]s, which is what makes the identity rename-proof
///
/// A [`TermName`] is the RECORD FIELD's own name — the one `<db>(rename)` renames FROM —
/// so two deployments of one schema compute the same subject for the same term. The per-database
/// spelling is a [`FieldName`](crate::FieldName), which is a different type for exactly this
/// reason, and it reaches no part of this identity: an order compared by rendered names would
/// refuse a legal pair the moment one column's rename collided with another column's name, and
/// would admit a repeat wherever two renames crossed.
///
/// This is the identity the emitted `<T>OrderBy::complete` already dedupes the key tail by, one
/// layer up, where it is spelled as a match on the VARIANT. One variant is one column at every
/// database and one path here, so the two readings of "the same subject" are one reading.
///
/// # It is compared by SEGMENTS and rendered for a human
///
/// Equality and hashing walk the segments. The dotted [`Display`](core::fmt::Display) exists so a
/// refusal can name the subject a client wrote, and it is PROSE: nothing parses it, nothing matches
/// on it, and no part of this type's identity passes through it. [`Path`](crate::Path) states no
/// joining convention at all for the neighbouring reason — there the join is a BACKEND's, and the
/// families disagree about it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SubjectPath(&'static [&'static TermName]);

impl SubjectPath {
  /// The subject naming these segments, root-first.
  ///
  /// `const` and `'static` together, for [`RecordAddress::new`](crate::RecordAddress::new)'s
  /// reason: a schema's subjects are declared once, with the schema, and building one per request
  /// is what the `'static` makes impossible. A `&[…]` written in a `let` is a temporary and
  /// `E0716`; inside a `const` ITEM the same expression is a constant and its address is the
  /// program's, which is the shape generated code writes. An inline `const { … }` block does not
  /// stand in for the item — the borrow inside it is still a temporary.
  ///
  /// The array's LENGTH is a const parameter so the empty path — a subject naming no column, which
  /// no walk could compare and no message could render — is a compile error rather than a value.
  #[inline]
  #[must_use]
  pub const fn new<const N: usize>(segments: &'static [&'static TermName; N]) -> Self {
    const { assert!(N > 0, "an ordering term names at least one segment") }
    Self(segments)
  }

  /// The segments naming this subject, root-first.
  #[inline]
  #[must_use]
  pub const fn segments(self) -> &'static [&'static TermName] {
    self.0
  }
}

impl core::fmt::Display for SubjectPath {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    let mut segments = self.0.iter();
    if let Some(first) = segments.next() {
      f.write_str(first)?;
    }
    for segment in segments {
      f.write_str(".")?;
      f.write_str(segment)?;
    }
    Ok(())
  }
}

/// The subject an ordering TERM names — implemented by every emitted `<T>OrderBy`.
///
/// A method rather than an associated constant: a term is a VALUE that has already chosen its
/// variant, and which subject it names is that choice. The direction it carries is the other half
/// and no part of the subject — `title ASC` and `title DESC` are one subject named twice, which is
/// the case the decode refuses.
///
/// It is gated on NOTHING, where [`Orderings`] is gated on the GraphQL binding. Generated code
/// lives in the DECLARING crate and cannot spell a feature of this one, so a trait an expansion
/// names has to exist in every build of it — the same split [`OrderDirection`](crate::OrderDirection)
/// already carries, where the enum is unconditional and only its wire derive rides the feature.
pub trait ToSubjectPath {
  /// Which subject this term orders by.
  fn subject_path(&self) -> SubjectPath;
}

/// An order as it arrived from a client: the terms it wrote, in the sequence it wrote them, each
/// naming a subject no other term names.
///
/// It is built by the [`InputType`](async_graphql::InputType) decode and nowhere else, which is
/// what makes the uniqueness a fact about every value of this type rather than a check somebody
/// remembers to run. The Rust order-builder API is a separate door and keeps taking a plain slice;
/// what guards THAT one is the partition frame, on the other side of the engine.
///
/// # It carries no `PartialEq`, and the absence is the design
///
/// An `IndexMap`'s own equality is a MAP's — order-insensitive — so a derived one here would report
/// two different orders as equal, which is the wrong answer for the one property this type exists
/// to preserve. Comparing orders means comparing sequences: iterate [`terms`](Self::terms).
#[cfg(feature = "async-graphql")]
#[derive(Debug, Clone)]
pub struct Orderings<T> {
  terms: IndexMap<SubjectPath, T>,
}

#[cfg(feature = "async-graphql")]
impl<T> Orderings<T> {
  /// The EMPTY order — what an absent `orderBy` and `orderBy: []` both mean.
  ///
  /// The KEY DEFAULT's one door: a resolver whose `orderBy` argument is `None` reaches this, hands
  /// the result to the emitted `<T>OrderBy::complete`, and gets the record's key ascending —
  /// exactly what a client writing `[]` gets, through exactly the same two calls.
  ///
  /// It is here rather than left to `unwrap_or_default` at each resolver so that the normalisation
  /// has ONE name a reader can go and look at, and so the sentence explaining it is attached to the
  /// thing rather than repeated per emission.
  #[inline]
  #[must_use]
  pub fn new() -> Self {
    Self {
      terms: IndexMap::new(),
    }
  }

  /// How many terms this order holds.
  #[inline]
  #[must_use]
  pub fn len(&self) -> usize {
    self.terms.len()
  }

  /// Whether this is the EMPTY order — the legal state a query that wrote no term is in, and not a
  /// refusal. See the module documentation for what requires a written order and where.
  #[inline]
  #[must_use]
  pub fn is_empty(&self) -> bool {
    self.terms.is_empty()
  }

  /// The terms, in the sequence the client wrote them.
  #[inline]
  pub fn terms(&self) -> impl ExactSizeIterator<Item = &T> {
    self.terms.values()
  }

  /// The term naming this subject, or `None` where the order does not name it.
  ///
  /// The lookup the keying buys: an order holds at most one term per subject, so asking about a
  /// subject has one answer rather than a list to fold.
  #[inline]
  #[must_use]
  pub fn term(&self, subject: SubjectPath) -> Option<&T> {
    self.terms.get(&subject)
  }

  /// The terms as the sequence a lowering takes, in the order they were written.
  #[inline]
  #[must_use]
  pub fn into_terms(self) -> Vec<T> {
    self.terms.into_values().collect()
  }
}

/// The empty order, which is the KEY DEFAULT — so `order.unwrap_or_default()` is the whole of what
/// a resolver does with an absent `orderBy`.
#[cfg(feature = "async-graphql")]
impl<T> Default for Orderings<T> {
  #[inline]
  fn default() -> Self {
    Self::new()
  }
}

/// Two terms of one order naming one subject — what the decode refuses with.
///
/// Opaque to construct: the decode is the only party that can mint one, because it is the only
/// party that has seen both positions. What a caught refusal can read is all three facts, and the
/// message renders them.
#[cfg(feature = "async-graphql")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RepeatedSubject {
  subject: SubjectPath,
  at: usize,
  first: usize,
}

#[cfg(feature = "async-graphql")]
impl RepeatedSubject {
  /// The subject two terms named.
  #[inline]
  #[must_use]
  pub const fn subject(&self) -> SubjectPath {
    self.subject
  }

  /// Where the REPEAT sits in the client's list, counting from zero.
  #[inline]
  #[must_use]
  pub const fn at(&self) -> usize {
    self.at
  }

  /// Where the term it repeats sits.
  #[inline]
  #[must_use]
  pub const fn first(&self) -> usize {
    self.first
  }
}

#[cfg(feature = "async-graphql")]
impl core::fmt::Display for RepeatedSubject {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    write!(
      f,
      "ordering term {} names `{}`, which term {} already orders by — name each subject once: a \
       second term over a subject cannot reorder anything, and the backends disagree about what it \
       does mean",
      self.at, self.subject, self.first
    )
  }
}

#[cfg(feature = "async-graphql")]
impl core::error::Error for RepeatedSubject {}

/// The wire door's own word: a client that named a subject twice is told so under
/// `REPEATED_ORDER_SUBJECT`, whatever the sentence beside it grows into.
#[cfg(feature = "async-graphql")]
impl super::ToErrorCode for RepeatedSubject {
  #[inline]
  fn error_code(&self) -> super::ErrorCode {
    super::ErrorCode::RepeatedOrderSubject
  }
}

/// The DECODE: the list a client wrote, walked once, refusing at the term that repeats a subject.
///
/// Everything except [`parse`](async_graphql::InputType::parse) mirrors what a `Vec<T>` of the same
/// term does, and mirrors it exactly — that is what makes the wrapper invisible in SDL. The name
/// this presents is a LIST TYPE REFERENCE (`[<T>OrderBy!]`) rather than a type name, so nothing is
/// registered for the wrapper itself and only `T` reaches the registry.
#[cfg(feature = "async-graphql")]
impl<T> async_graphql::InputType for Orderings<T>
where
  T: async_graphql::InputType + ToSubjectPath,
{
  type RawValueType = Self;

  fn type_name() -> std::borrow::Cow<'static, str> {
    std::borrow::Cow::Owned(format!("[{}]", T::qualified_type_name()))
  }

  fn qualified_type_name() -> String {
    format!("[{}]!", T::qualified_type_name())
  }

  fn create_type_info(registry: &mut async_graphql::registry::Registry) -> String {
    T::create_type_info(registry);
    Self::qualified_type_name()
  }

  fn parse(value: Option<async_graphql::Value>) -> async_graphql::InputValueResult<Self> {
    let written = match value.unwrap_or_default() {
      async_graphql::Value::List(written) => written,
      // GraphQL's own list input coercion: a lone value is the one-element list. Mirrored from
      // `Vec`'s decode, because a client that may write `order: {title: ASC}` against a `Vec` must
      // be able to write it against this.
      lone => vec![lone],
    };
    let mut terms = IndexMap::with_capacity(written.len());
    for (at, value) in written.into_iter().enumerate() {
      let term = T::parse(Some(value)).map_err(async_graphql::InputValueError::propagate)?;
      let subject = term.subject_path();
      if let Some(first) = terms.get_index_of(&subject) {
        // The refusal carries its own STABLE CODE — `REPEATED_ORDER_SUBJECT` — beside the sentence,
        // and the code is what a client matches on. See [`code`](super::code) for why the message
        // is not a contract and the word is.
        return Err(super::refused_input(RepeatedSubject { subject, at, first }));
      }
      terms.insert(subject, term);
    }
    Ok(Self { terms })
  }

  fn to_value(&self) -> async_graphql::Value {
    async_graphql::Value::List(
      self
        .terms
        .values()
        .map(async_graphql::InputType::to_value)
        .collect(),
    )
  }

  fn as_raw_value(&self) -> Option<&Self::RawValueType> {
    Some(self)
  }
}

#[cfg(test)]
mod tests;