ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! **I-3's WIRE HALF** — the SDL face `<I>GraphqlOutput` wears: a GraphQL `interface`, the
//! `implements` clause each member's object gains from it, and the `__typename` a client reads a
//! row's provenance off.
//!
//! # D-1, in one sentence: the interface DECLARES and the records IMPLEMENT
//!
//! *The interface's SDL face is `interface` + `implements`. The declared common-field contract
//! publishes AS the interface's fields — common fields queryable fragment-free, member-specific via
//! inline fragments.* That is one `MetaType::Interface` carrying one entry per contract field, and
//! one `add_implements` per member so `type Take implements Media` renders on the member's own type.
//!
//! ```text
//! interface Media { slate: String!, frames: Int! }
//! type Reel implements Media { slate: String!, frames: Int!, … }
//! type Tape implements Media { slate: String!, frames: Int!, … }
//! ```
//!
//! # D-4, in one field nobody minted: `__typename`
//!
//! *No interface get leg … provenance is served by the SPEC'S OWN mechanism, not a minted field.*
//! `OutputType::introspection_type_name` is that mechanism, and the emission pins it PER ARM by
//! delegating to the member's own answer — so a member renamed through `output(rename = "…")` moves
//! its `__typename` and this face follows without knowing. There is no `kind` field beside it: a
//! duplicate of `__typename` is schema bloat that tooling cannot see.
//!
//! What a caller does with it is the flow this face exists to make possible:
//!
//! ```text
//! query { media(first: 10) { edges { node { __typename ... on Reel { id } } } } }
//!                                          └── "Reel"  ⇒ the next by-id call is `reel(id:)`
//! ```
//!
//! The CONCRETE get leg's name derives from the same published name the `__typename` carries — one
//! tower, so the two cannot drift.
//!
//! # It is HAND-WRITTEN, and the reason is a measured one
//!
//! `#[derive(Interface)]` cannot be attached here. The derive resolves each interface field by
//! calling `obj.<method>(ctx)` on the member's payload and then `.await.map_err(…)` on the result —
//! so it demands of every member's output object a method that TAKES a context and RETURNS a
//! `Result`. The emitted output faces take no context and return the value itself (`emit::wire`'s
//! `output_face`), which is what makes their accessors `const`-adjacent borrows rather than
//! resolvers. Changing every record's output method to satisfy a foreign derive would be a whole
//! corpus paying for one type's convenience.
//!
//! What is written instead is that derive's own output at the one place it could not be attached —
//! the posture the two INPUT faces already take — with one deliberate improvement: `resolve_field`
//! DELEGATES to the member's container rather than dispatching per field. That is also what
//! `ContainerType::collect_all_fields`'s own documentation asks of an interface (*interfaces and
//! unions must call it on their internal type*), and it is what makes an inline fragment on a member
//! resolve the member's PRIVATE fields — which is the other half of D-1.
//!
//! # The delegation has a PRICE, and it is stated rather than hidden
//!
//! Because a plain field selection on an interface value is resolved by the MEMBER's container, the
//! interface's published field name must be the name that member publishes. That holds for every
//! declaration whose members carry the contract's columns under the contract's own names — which is
//! every declaration the framework can check, the row equations being written on exactly that. A
//! member that keeps a shared column under ANOTHER name (`members(<V>(field = "…"))`) publishes that
//! other name on its own object, and this face has no way to publish two. See the round's flag: the
//! rename is a STORAGE-side fact today and the wire half of it is a round of its own.
//!
//! # The STORED tier publishes, and the computed tier is a flagged gap
//!
//! `<I>Derivations` is implemented BY HAND on a member's output type, outside the `#[Object]` block
//! that publishes that object's fields — so a computed contract field is a field the MEMBER's SDL
//! does not have. Publishing it on the interface would declare an `implements` a member does not
//! satisfy. So the face publishes the STORED tier, which is exactly the tier every member's object
//! is known to carry.
//!
//! # `boxed-trait`
//!
//! async-graphql's `ContainerType` and `OutputType` change SHAPE under its non-default `boxed-trait`
//! feature — `#[async_trait]` instead of `-> impl Future + Send` — and its own derives read that
//! feature with `cfg!`, which an emission in a DECLARING crate cannot do. `ingraph` takes
//! async-graphql with `default-features = false` and never enables it; a build that turns it on
//! elsewhere in its graph gets `E0195` here. Stated rather than discovered.

use quote::quote;

use crate::{emit::leading, interface::InterfaceModel};

#[cfg(test)]
mod tests;

impl InterfaceModel {
  /// The SDL face, inside the binding gate — or nothing, for an interface with no stored contract
  /// to publish.
  ///
  /// The condition is [`projects`](Self::projects)'s own: an interface promising no stored column
  /// has no field for the interface type to declare, and a GraphQL interface with no field is not a
  /// type. It also has no page, so nothing would return one.
  pub(crate) fn sdl_face(&self) -> proc_macro2::TokenStream {
    if !self.projects() {
      return quote!();
    }
    let interface = &self.name;
    let name = super::default_output_name(interface);
    let published = interface.to_string();
    let gate = self.framework(&["gate"], "if_async_graphql");
    let ag = self.framework(&[], "async_graphql");
    let crossing = self.framework(&["graphql"], "ToGraphqlOutput");
    let transformer = self.framework(&["transform"], "Transformer");
    let graphql = self.framework(&["transform"], "Graphql");

    // Every member's OUTPUT type, as a family projection — the same one `<I>GraphqlOutput`'s own
    // variants carry, so the type this registers and the type that variant holds are one type by
    // construction rather than by two spellings agreeing.
    let outputs: Vec<proc_macro2::TokenStream> = self
      .members
      .iter()
      .map(|member| {
        let ty = &member.ty;
        quote!(<<#ty as #transformer>::Graphql as #graphql>::Output)
      })
      .collect();

    let registrations = outputs.iter().map(|output| {
      quote! {
        <#output as #ag::OutputType>::create_type_info(__ingraph_registry);
        #ag::registry::Registry::add_implements(
          __ingraph_registry,
          &<#output as #ag::OutputType>::type_name(),
          #published,
        );
      }
    });
    let possible = outputs.iter().map(|output| {
      quote! {
        #ag::indexmap::IndexSet::insert(
          &mut __ingraph_possible,
          ::std::borrow::Cow::into_owned(<#output as #ag::OutputType>::type_name()),
        );
      }
    });

    // ONE entry per STORED contract field. The published name is the framework's camelCase over the
    // contract's own word — an interface's grammar carries no per-field rename tier — and the TYPE
    // is the member's own crossing, so the interface declares the field at the type its members
    // publish it at rather than at a domain type a schema never sees.
    let fields = self.stored().map(|field| {
      let word = crate::emit::wire::wire_member(&field.name);
      let ty = &field.ty;
      quote! {
        #ag::indexmap::IndexMap::insert(
          &mut __ingraph_fields,
          ::std::string::String::from(#word),
          #ag::registry::MetaField {
            name: ::std::string::String::from(#word),
            description: ::core::option::Option::None,
            args: #ag::indexmap::IndexMap::new(),
            ty: <<#ty as #crossing>::Output<'static> as #ag::OutputType>::create_type_info(
              __ingraph_registry,
            ),
            deprecation: #ag::registry::Deprecation::NoDeprecated,
            cache_control: ::core::default::Default::default(),
            external: false,
            requires: ::core::option::Option::None,
            provides: ::core::option::Option::None,
            visible: ::core::option::Option::None,
            shareable: false,
            inaccessible: false,
            tags: ::std::vec::Vec::new(),
            override_from: ::core::option::Option::None,
            compute_complexity: ::core::option::Option::None,
            directive_invocations: ::std::vec::Vec::new(),
            requires_scopes: ::std::vec::Vec::new(),
          },
        );
      }
    });

    let resolves = self.members.iter().map(|member| {
      let variant = &member.ident;
      quote! {
        Self::#variant(__ingraph_member) => {
          #ag::resolver_utils::ContainerType::resolve_field(__ingraph_member, __ingraph_ctx).await
        }
      }
    });
    let collects = self.members.iter().map(|member| {
      let variant = &member.ident;
      quote! {
        Self::#variant(__ingraph_member) => {
          #ag::resolver_utils::ContainerType::collect_all_fields(
            __ingraph_member,
            __ingraph_ctx,
            __ingraph_fields,
          )
        }
      }
    });
    let typenames = self.members.iter().map(|member| {
      let variant = &member.ident;
      quote! {
        Self::#variant(__ingraph_member) => {
          #ag::OutputType::introspection_type_name(__ingraph_member)
        }
      }
    });

    let resolve_doc = leading(
      "One field of a selection on this interface, resolved by the MEMBER the row came from.\n\nThe \
       delegation is what an interface's container is documented to do, and it is what makes an \
       inline fragment on a member reach that member's PRIVATE fields. The price is stated in this \
       module's note: the interface's published field name is the name its members publish.",
    );
    let collect_doc = leading(
      "The whole selection set, collected against the member the row came from — `ContainerType`'s \
       own instruction to an interface, verbatim.",
    );
    let typename_doc = leading(
      "`__typename` — the PUBLISHED name of the member this row came from, read off that member's \
       own output face.\n\nThis is the provenance the design ruled instead of a minted `kind` \
       field, and delegating is what pins it per arm: a member renamed through \
       `output(rename = \"…\")` moves its own `__typename` and this answer follows. The CONCRETE \
       by-id field a caller reaches for next is named from the same published word, so the two \
       cannot drift.",
    );

    quote! {
      #gate! {
        #[automatically_derived]
        impl #ag::resolver_utils::ContainerType for #name {
          #[doc = #resolve_doc]
          async fn resolve_field(
            &self,
            __ingraph_ctx: &#ag::Context<'_>,
          ) -> #ag::ServerResult<::core::option::Option<#ag::Value>> {
            match self {
              #(#resolves)*
            }
          }

          #[doc = #collect_doc]
          fn collect_all_fields<'__ingraph_sel>(
            &'__ingraph_sel self,
            __ingraph_ctx: &#ag::ContextSelectionSet<'__ingraph_sel>,
            __ingraph_fields: &mut #ag::resolver_utils::Fields<'__ingraph_sel>,
          ) -> #ag::ServerResult<()> {
            match self {
              #(#collects)*
            }
          }
        }

        #[automatically_derived]
        impl #ag::OutputType for #name {
          #[inline]
          fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
            ::std::borrow::Cow::Borrowed(#published)
          }

          #[doc = #typename_doc]
          fn introspection_type_name(
            &self,
          ) -> ::std::borrow::Cow<'static, ::core::primitive::str> {
            match self {
              #(#typenames)*
            }
          }

          fn create_type_info(
            __ingraph_registry: &mut #ag::registry::Registry,
          ) -> ::std::string::String {
            #ag::registry::Registry::create_output_type::<Self, _>(
              __ingraph_registry,
              #ag::registry::MetaTypeId::Interface,
              |__ingraph_registry| {
                // The members REGISTER FIRST, and each is told it implements this name — which is
                // the whole of the `implements` clause: async-graphql builds that clause from the
                // registry's own table rather than from anything on the object's side.
                #(#registrations)*
                #ag::registry::MetaType::Interface {
                  name: ::std::string::String::from(#published),
                  description: ::core::option::Option::None,
                  fields: {
                    let mut __ingraph_fields = #ag::indexmap::IndexMap::new();
                    #(#fields)*
                    __ingraph_fields
                  },
                  possible_types: {
                    let mut __ingraph_possible = #ag::indexmap::IndexSet::new();
                    #(#possible)*
                    __ingraph_possible
                  },
                  extends: false,
                  keys: ::core::option::Option::None,
                  visible: ::core::option::Option::None,
                  inaccessible: false,
                  tags: ::std::vec::Vec::new(),
                  rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
                  directive_invocations: ::std::vec::Vec::new(),
                  requires_scopes: ::std::vec::Vec::new(),
                }
              },
            )
          }

          async fn resolve(
            &self,
            __ingraph_ctx: &#ag::ContextSelectionSet<'_>,
            __ingraph_field: &#ag::Positioned<#ag::parser::types::Field>,
          ) -> #ag::ServerResult<#ag::Value> {
            let _ = __ingraph_field;
            #ag::resolver_utils::resolve_container(__ingraph_ctx, self).await
          }
        }

        #[automatically_derived]
        impl #ag::InterfaceType for #name {}
      }
    }
  }
}