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 HOLDING ADAPTER: [`Crossed`] — an owned value that renders as whatever
//! [`ToGraphqlOutput`](super::ToGraphqlOutput) says its type crosses to.
//!
//! # The contract this exists to satisfy
//!
//! async-graphql resolves through `OutputType::resolve(&self, …)`, so whatever a resolver returns is
//! rendered from a BORROW of it. A field that is a PLACE serves that contract for free: `&self.width`
//! is a borrow of storage, the resolver returns `<Ty as ToGraphqlOutput>::Output<'_>`, and every arm
//! of the map works — the borrowing ones included, which is what keeps a published column free of a
//! clone per field of every response.
//!
//! A field that is not a place cannot. The REWRITE mode's manifest column is read by calling the
//! remote's own accessor, so the value arrives by value and the only reference available is one to a
//! temporary. MEASURED, at async-graphql 7.2 against this crate's own map:
//!
//! | written | rustc |
//! |---|---|
//! | `to_graphql_output(&self.label())` returning `Output<'_>` | `E0515: cannot return value referencing temporary value` |
//! | the same, returning `Output<'static>` | `E0716: temporary value dropped while borrowed` |
//! | `async fn … -> String { self.label() }` | compiles |
//!
//! The third row is what the emission shipped first, and it moved the OBLIGATION: returning the
//! domain type bare asks `async_graphql::OutputType` of it rather than
//! [`ToGraphqlOutput`](super::ToGraphqlOutput), and the two agree everywhere except where this
//! crate's map exists — `u128: OutputType` is unsatisfied (measured), and a `Vec<u8>` reached a
//! schema as `[Int!]` rather than as the blob's own carrier. So one tier published a `u128` column as
//! `u128!` and another failed to compile at the same declared type.
//!
//! # Ownership moves into the RETURN TYPE, not into the map
//!
//! The other road was an OWNED arm on [`ToGraphqlOutput`](super::ToGraphqlOutput) — a second
//! associated form beside `Output<'a>`, written on every row. It was refused: the map is a total
//! table with one row per declarable type and a downstream row per foreign one, and a second arm
//! doubles every one of them for the sake of one caller's lifetime problem.
//!
//! What this module does instead is put the ownership where the problem is. `Crossed<T>` MOVES the
//! freshly-made value in, lives for the resolver's return, and at `resolve` time borrows its own
//! field and projects — which is the borrow the contract wanted, at an address that outlives the
//! call. The map keeps its single entrance and not one row changes.
//!
//! # Held and wrapped therefore RENDER ALIKE
//!
//! Every name a schema reads off `Crossed<T>` is `T`'s own projection's — `type_name`,
//! `qualified_type_name`, `create_type_info` and `introspection_type_name` all delegate — so the
//! adapter is INVISIBLE in the SDL. A `u128` column publishes `u128!` whether it is held or wrapped,
//! a `Vec<u8>` column publishes the blob carrier at both, and a nullable column publishes nullable
//! at both, `Option`'s own `qualified_type_name` being what answers.
//!
//! # Who needs it, and who turned out not to
//!
//! Three declarations wrap a foreign type — `entity`, `record` and the field-fragment tier — and only
//! the last of them meets this wall. SURVEYED, by expanding a `record(remote = "…", graphql(…))`:
//! a record's and an entity's wire face is written on a MINTED `<E>GraphqlOutput`, a plain struct
//! holding the columns it projected out of the row, so every resolver there reads a real place and
//! returns the borrowing arm whatever mode declared the record. The crossing to the manifest has
//! already happened, once, at hydration. A fragment has no such projection — its `#[Object]` is on
//! the declaration itself — which is what makes the wrapper's own field the thing being resolved
//! from.
//!
//! One near neighbour solves the same problem another way and is left alone: a vocabulary mirror's
//! PROMOTED delegate object hand-writes `ContainerType::resolve_field`, so it can bind the delegated
//! method's answer to a local and cross a borrow of THAT. A hand-written resolver has a scope to put
//! the value in; an `#[Object]` method has only its return type, which is why this type exists.
//!
//! # What it costs, and the one refinement it defers
//!
//! One move of the owned value and no second conversion: the crossing runs exactly once, at
//! `resolve`, on a borrow of the moved value — so a wrapped path pays what a held one pays plus the
//! move the reader had already made.
//!
//! What it does not yet do is notice when the move was avoidable. An upstream accessor that already
//! hands back a BORROW could be projected straight through, with no adapter and no move at all; the
//! rewrite reads every data column by value today, so the question does not arise at this tier yet.
//! Recorded here rather than built, and it is a REFINEMENT rather than a correction — the SDL is the
//! same either way.

use async_graphql::{
  ContextSelectionSet, OutputType, Positioned, ServerResult, Value, parser::types::Field,
  registry::Registry,
};

use super::ToGraphqlOutput;

#[cfg(test)]
mod tests;

/// A value a wire face MADE, holding it until the resolver renders it — and rendering as
/// [`ToGraphqlOutput`](super::ToGraphqlOutput) says its type crosses.
///
/// The field is public because the values that need it are built inside expansions in a DECLARING
/// crate, and a hand-written resolver in the same position spells it the same way.
///
/// # `Send + Sync + 'static` are three obligations and each is spent
///
/// `Send + Sync` because `OutputType` demands both of the type that carries it, and this one is a
/// newtype over `T`. `'static` because [`type_name`](OutputType::type_name) and
/// [`create_type_info`](OutputType::create_type_info) are asked with no value in hand: naming the
/// projected form there needs `Output<'static>`, and `T: 'static` is the one way to have it. It is
/// the pair [`WireScore`](crate::WireScore) already spends one consumption point over, and the two
/// are stated separately rather than merged because that trait carries a DOCTRINE beside the bound —
/// a score's currency — which a fragment's field is not.
///
/// # Examples
///
/// A `u128` has no `async_graphql::OutputType` row anywhere and crosses through this crate's own
/// carrier, so the adapter is what lets a resolver ANSWER with one it just computed:
///
/// ```
/// # #[cfg(feature = "async-graphql")]
/// # fn main() {
/// use async_graphql::OutputType;
/// use ingraph::Crossed;
///
/// assert_eq!(<Crossed<u128> as OutputType>::type_name(), "u128");
/// assert_eq!(<Crossed<u128> as OutputType>::qualified_type_name(), "u128!");
///
/// // A nullable column stays nullable: the projection's own qualified name answers.
/// assert_eq!(<Crossed<Option<u128>> as OutputType>::qualified_type_name(), "u128");
/// # }
/// # #[cfg(not(feature = "async-graphql"))]
/// # fn main() {}
/// ```
///
/// A type with no crossing row is refused where the adapter is spent, naming
/// [`ToGraphqlOutput`](super::ToGraphqlOutput) — the row that is missing:
///
/// ```compile_fail
/// use async_graphql::OutputType;
///
/// struct Unregistered;
///
/// fn main() {
///   let _ = <ingraph::Crossed<Unregistered> as OutputType>::type_name();
/// }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Crossed<T>(pub T);

/// The delegation, in full: FOUR names read off the projection and one value crossed from a borrow of
/// the held one.
///
/// [`qualified_type_name`](OutputType::qualified_type_name) is delegated rather than left to the
/// trait's default, and that is the nullable column's whole correctness: the default appends `!` to
/// [`type_name`](OutputType::type_name), where `Option`'s own row publishes the bare name. A default
/// here would have made every wrapped optional column non-null in the SDL and null at run time.
///
/// [`introspection_type_name`](OutputType::introspection_type_name) is delegated for the same reason
/// one step further out: an interface or a union answers `__typename` with the CONCRETE member, which
/// only the projected value knows. The default would have answered with the static name.
impl<T> OutputType for Crossed<T>
where
  T: ToGraphqlOutput + Send + Sync + 'static,
  for<'a> <T as ToGraphqlOutput>::Output<'a>: OutputType,
{
  #[inline]
  fn type_name() -> std::borrow::Cow<'static, str> {
    <<T as ToGraphqlOutput>::Output<'static> as OutputType>::type_name()
  }

  #[inline]
  fn qualified_type_name() -> String {
    <<T as ToGraphqlOutput>::Output<'static> as OutputType>::qualified_type_name()
  }

  #[inline]
  fn introspection_type_name(&self) -> std::borrow::Cow<'static, str> {
    <<T as ToGraphqlOutput>::Output<'_> as OutputType>::introspection_type_name(
      &<T as ToGraphqlOutput>::to_graphql_output(&self.0),
    )
  }

  #[inline]
  fn create_type_info(registry: &mut Registry) -> String {
    <<T as ToGraphqlOutput>::Output<'static> as OutputType>::create_type_info(registry)
  }

  async fn resolve(
    &self,
    ctx: &ContextSelectionSet<'_>,
    field: &Positioned<Field>,
  ) -> ServerResult<Value> {
    // The BORROW the contract wanted, at an address that outlives the call: `self.0` is the moved
    // value, so the projection this crossing builds points into the adapter rather than into a
    // temporary — which is the whole of what this type is for.
    <<T as ToGraphqlOutput>::Output<'_> as OutputType>::resolve(
      &<T as ToGraphqlOutput>::to_graphql_output(&self.0),
      ctx,
      field,
    )
    .await
  }
}