ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The MUTATION NODE's WIRE FACE: one root field per exchange, and the resolver behind each.
//!
//! ```text
//! type Mutation {
//!   addWatch(input: AddWatchInput!): AddResponse!   # WatchOpsMutations::__async_graphql_add
//!   remove(input: RemoveWatchInput!): Boolean!      # … and a `()` answer is `Boolean!`
//!   reindex(input: ReindexInput!): Boolean!
//! }
//! ```
//!
//! # PER-FIELD, and the shape is what deleted a whole layer
//!
//! Every exchange is its own root field with its own handler, its own answer and its own declared
//! failure. So there is no node-level request union, no node-level response union, and — the part
//! that matters — NO WAY TO ANSWER THE WRONG COMMAND: the arm a runtime check used to look for is
//! unwritable rather than guarded, because the field a client wrote IS the handler that runs.
//!
//! # WHAT A RESOLVER DOES, in the order it does it
//!
//! 1. **Find the source's line first.** `ctx.data::<Commands<…>>()` before anything else, so a schema
//!    that never mounted this node refuses with nothing done. This is the ordering that matters most
//!    in the whole file: every later step has an effect, and the one failure that cannot be hoisted
//!    is the source dying between the handler's answer and the forward.
//! 2. **Take the grants**, in the order `context(resource("…"), …)` wrote them.
//! 3. **Mint the command** from a CLONE of the request, before the handler spends it.
//! 4. **Call the handler through the node's own per-exchange call**, which is where the three-tier
//!    contract is cast: that call binds the handler to the exact type the `error(…)` word chose, so
//!    a body that wears another signature is `E0308` at the `handler` path word rather than deep
//!    inside these tokens. It is emitted ONCE and spent by both faces — see
//!    [`face`](super::face), which states why a second cast here would report one mistake twice.
//! 5. **Render a failure** under the heading its declaration wrote — the one-code-head law, which
//!    lives in [`refused_exchange`](../../../ingraph/fn.refused_exchange.html).
//! 6. **Forward, ONE WAY and ONLY ON SUCCESS.** A change that failed has no living application, so
//!    nothing is sent; a change that succeeded is minted as its command variant and handed to the
//!    source's `Control` line, which never answers.
//!
//! # A DECLARED EXCHANGE'S REQUEST IS `Clone`, and the bound is the forward's
//!
//! Step 3 clones. That is a real requirement on every request type a declaration names, and it is
//! enforced HERE — at the resolver — rather than at the declaration, so it is worth saying plainly
//! what it costs and why it is the shape it is.
//!
//! The command carries the REQUEST (the record's own ruling: what travels to the living application
//! is what was asked for) and the handler takes that request BY VALUE (the three-tier signature's
//! own ruling). Two parties want one value, and one of them runs first, so a copy is made before the
//! handler spends it.
//!
//! It costs a declaration almost nothing, and the reason is what a request already IS: a wire input
//! object, which async-graphql's own `InputType` already requires be `Send + Sync + Sized` and which
//! is by construction a bag of owned, decoded values with no borrow in it. `Clone` is the nature of
//! such a thing rather than an imposition on it.
//!
//! The two alternatives were both worse and both contradict a ruling. Handing the handler
//! `&Request` contradicts the signature the three tiers are cast to — and would make a handler
//! unable to consume what it was given, which is what most of them want. Forwarding the RESPONSE
//! instead contradicts what a command IS: the living application applies what was ASKED FOR, and a
//! response is what came back.
//!
//! # The door is keyed by the COMMAND TYPE, and needs no wrapper
//!
//! [`SqlDoor`](../../../ingraph/graphql/struct.SqlDoor.html) exists because `ctx.data` is a lookup on
//! a concrete type and a POOL is not one — two records over one database would collide. Nothing here
//! has that problem: a node mints a command enum of its own, one node is one source's command face,
//! so `Commands<WatchOpsCommand>` is already the precise key. An application installs it with
//! `Schema::build(…).data(commands)` and the resolver reads it back.
//!
//! # `()` ANSWERS AS `Boolean!`, and the pair spelling is where that is read
//!
//! An exchange written `(Request, ())` says *it worked* and nothing else, and async-graphql has no
//! `OutputType` for `()` — so the field publishes `Boolean!` and answers `true`. It is read off the
//! PAIR, syntactically, because that is where the emission can see it: a field type is otherwise an
//! opaque `Mutation` implementor whose `Response` this pass cannot inspect. An exchange written as a
//! type of its own that answers nothing writes [`Noop`](../../../ingraph/struct.Noop.html) — the
//! WIRE-level nothing, which exists precisely because a published position has to render.

use proc_macro2::TokenStream;
use quote::{format_ident, quote, quote_spanned};

use super::{DeclaredError, ExchangeModel, MutationModel};
use crate::{emit::wire::wire_member, method::wire_method};

#[cfg(test)]
mod tests;

impl MutationModel {
  /// The wire unit's name — the node's own, with `Mutations` after it.
  ///
  /// [`default_queries_name`](crate::model::default_queries_name)'s shape one family over, and
  /// derived for its reason: the node's name IS the vocabulary's name, and a second word for it
  /// would be a name two spellings could disagree about.
  #[must_use]
  pub fn unit_name(&self) -> syn::Ident {
    format_ident!("{}Mutations", self.name)
  }

  /// The wire face, or nothing at all for a node with no `graphql(…)` word.
  ///
  /// TWO items, split exactly as a record's query unit is: the unit TYPE is unconditional and the
  /// `#[Object]` face rides the binding gate. A build without the binding therefore still has the
  /// type an application mounts, and what it does not have is a schema over it — which is the
  /// honest shape, since the type is a name in somebody else's code and the face is this crate's.
  pub(super) fn wire(&self) -> TokenStream {
    if self.graphql.is_empty() {
      return TokenStream::new();
    }
    let unit = self.unit();
    let face = self.face();
    quote! {
      #unit
      #face
    }
  }

  /// The mountable UNIT: an empty type whose `#[Object]` face carries this node's root fields.
  ///
  /// The `#[Object]` cannot go on the node itself, and the reason is structural rather than
  /// stylistic: a resolver is a method on a VALUE, a schema is built from a `Default`, and a mutation
  /// node's fields are exchange types nobody constructs. The node is a declaration vehicle; this is
  /// the thing a root folds.
  fn unit(&self) -> TokenStream {
    let vis = &self.vis;
    let name = self.unit_name();
    let node = &self.name;
    let doc = crate::emit::leading(&format!(
      "The root fields a [`{node}`] answers — one per exchange it declared.\n\nMounted by folding \
       it into a graph's root mutation; it holds nothing, and it reaches the source it controls \
       through the command line the schema was built with."
    ));
    quote! {
      #[doc = #doc]
      #[derive(
        ::core::fmt::Debug,
        ::core::clone::Clone,
        ::core::marker::Copy,
        ::core::default::Default,
      )]
      #vis struct #name;
    }
  }

  /// The `#[Object]` over every exchange, inside the binding gate.
  fn face(&self) -> TokenStream {
    let krate = &self.krate;
    let name = self.unit_name();
    let sdl = name.to_string();
    let ag = crate::emit::framework(krate, &[], "async_graphql");
    let shelf = crate::emit::vendored(krate, "async_graphql");
    let gate = crate::emit::framework(krate, &["gate"], "if_async_graphql");
    let prelude = crate::emit::wire::prelude();
    let fields = self
      .exchanges
      .iter()
      .map(|exchange| self.resolver(exchange));
    quote! {
      #gate! {
        const _: () = {
          #prelude

          #[#ag::Object(crate = #shelf, name = #sdl)]
          impl #name {
            #(#fields)*
          }
        };
      }
    }
  }

  /// ONE EXCHANGE's resolver — see the module note for the order of what it does.
  #[expect(
    clippy::too_many_lines,
    reason = "one resolver is one statement list, and the six steps the module note tabulates are \
              exactly the six blocks below — splitting them into helpers would move the ORDER, \
              which is the load-bearing part, out of the one place it can be read"
  )]
  fn resolver(&self, exchange: &ExchangeModel) -> TokenStream {
    let krate = &self.krate;
    let ag = crate::emit::framework(krate, &[], "async_graphql");
    let mutation = crate::emit::framework(krate, &["source"], "Mutation");
    let node = crate::emit::framework(krate, &["source"], "MutationNode");
    let commands = crate::emit::framework(krate, &["source"], "Commands");
    let shared = crate::emit::framework(krate, &["resource"], "Shared");
    let refused = crate::emit::framework(krate, &["graphql"], "refused");
    let refused_exchange = crate::emit::framework(krate, &["graphql"], "refused_exchange");
    let unreachable = crate::emit::framework(krate, &["drive"], "QueryError");

    let ty = &exchange.ty;
    let name = &self.name;
    let command = self.command_name();
    let variant = exchange.variant();
    let field = exchange.published();
    let method = wire_method(&format_ident!("{}", exchange.named()));
    let ctx = wire_method(&format_ident!("ctx"));
    let input = wire_method(&format_ident!("input"));

    let request = quote!(<#ty as #mutation>::Request);
    // The RESPONSE, and the one place a `()` answer is read: the pair spelling is where this pass
    // can see it, per the module note.
    let unit_answer = exchange.answers_nothing();
    let response = if unit_answer {
      quote!(::core::primitive::bool)
    } else {
      quote!(<#ty as #mutation>::Response)
    };

    // THE LINE, first — a schema that never mounted this node refuses with nothing done.
    let line = quote! {
      let __ingraph_line = #ag::Context::data::<#commands<<#name as #node>::Command>>(#ctx)
        .map_err(|_| #refused(&#unreachable::UnreachableSource))?;
    };

    // THE GRANTS, in the order the declaration wrote them, and nothing at all where it wrote none.
    let granted: Vec<syn::Ident> = (0..exchange.handler.context.len())
      .map(|at| format_ident!("__ingraph_granted_{at}"))
      .collect();
    let grants = exchange
      .handler
      .context
      .iter()
      .zip(&granted)
      .map(|(resource, held)| {
        quote! {
          let #held = #ag::Context::data::<#shared<#resource>>(#ctx)?;
        }
      });
    let arguments = granted
      .iter()
      .zip(&exchange.handler.context)
      .map(|(held, resource)| quote!(#shared::<#resource>::get(#held)));

    // THE COMMAND, minted BEFORE the handler spends the request — the forward carries what was
    // asked for, and the handler takes it by value.
    let at = exchange.field.span();
    let clone = quote_spanned!(at=> ::core::clone::Clone::clone(&#input));
    // The VARIANT is named on the enum itself and not through `<Node as MutationNode>::Command`,
    // which the LINE above does spell: a projection is a type and a variant is resolved off a type
    // PATH, so the two positions take the two spellings — the type one proving the row exists, the
    // constructor one naming the enum this same expansion minted a line earlier.
    let minted = quote! {
      let __ingraph_command = #command::#variant(#clone);
    };

    // THE CALL, through the node's OWN per-exchange call — the one place the three-tier signature
    // is cast, and it is spent here and by the assembled face. So a body that does not wear the
    // signature its declaration chose is refused ONCE, at the `handler` path word, however many
    // faces the node happens to publish.
    let path = &exchange.handler.path;
    let called = exchange.call_name();
    let awaited = exchange.handler.awaited.then(|| quote!(.await));
    let call = quote! {
      #name::#called(#(#arguments,)* #input) #awaited
    };
    let (outcome, answer) = match &exchange.handler.error {
      None => (
        quote! {
          let __ingraph_answer = #call;
        },
        quote!(__ingraph_answer),
      ),
      Some(declared) => {
        let render = match declared {
          DeclaredError::Rich { code, .. } => {
            let code = optional(code.as_ref());
            quote!(#refused_exchange(#code, &__ingraph_refusal))
          }
          DeclaredError::Canned { message, code } => {
            let code = optional(code.as_ref());
            quote! {{
              // The canned failure's whole content is the DECLARATION's, so the handler's own
              // `Err(())` is read for its POSITION and nothing else.
              let () = __ingraph_refusal;
              #refused_exchange(#code, #message)
            }}
          }
        };
        (
          quote! {
            let __ingraph_outcome = #call;
            let __ingraph_answer = match __ingraph_outcome {
              ::core::result::Result::Ok(__ingraph_answer) => __ingraph_answer,
              ::core::result::Result::Err(__ingraph_refusal) => {
                return ::core::result::Result::Err(#render);
              }
            };
          },
          quote!(__ingraph_answer),
        )
      }
    };

    // THE ANSWER: an exchange that says only *it worked* answers `true`, and its own `()` is read
    // out through an irrefutable pattern so the binding is spent rather than merely dropped.
    let answered = if unit_answer {
      quote! {
        let () = #answer;
        ::core::result::Result::Ok(true)
      }
    } else {
      quote!(::core::result::Result::Ok(#answer))
    };

    let doc = crate::emit::leading(&format!(
      "The `{field}` exchange — validated and answered by `{handler}`, then applied by the source \
       this node controls.",
      handler = quote!(#path).to_string().replace(' ', ""),
    ));
    quote! {
      #[doc = #doc]
      #[graphql(name = #field)]
      async fn #method(
        &self,
        #ctx: &#ag::Context<'_>,
        #[graphql(name = "input")] #input: #request,
      ) -> #ag::Result<#response> {
        #line
        #(#grants)*
        #minted
        #outcome
        // ONE WAY, and only on success: the answer was already given, and what travels here is the
        // change to APPLY. A source eats it and never replies.
        if #commands::say_async(__ingraph_line, __ingraph_command).await.is_err() {
          return ::core::result::Result::Err(#refused(&#unreachable::UnreachableSource));
        }
        #answered
      }
    }
  }
}

impl ExchangeModel {
  /// What the wire publishes this exchange as: its `rename = "…"` word, or its field name with a
  /// lower-case initial.
  ///
  /// The convention lives HERE and not in the declaration record, which answers `None` for an
  /// unrenamed field on purpose — what an unrenamed field is PUBLISHED as is the binding's decision,
  /// and the record putting its own guess there would be the record deciding it.
  ///
  /// The fallback is [`wire_member`], which is the crate's ONE answer to *what a client sees where
  /// nothing was written* — the same camelCase the record family's own faces fall back on, read from
  /// the same function, so a mutation field and a record field never come to disagree about it.
  #[must_use]
  pub fn published(&self) -> String {
    match &self.rename {
      Some(rename) => rename.value(),
      None => wire_member(&self.field),
    }
  }

  /// Whether this exchange answers NOTHING — the `(Request, ())` pair, and only that.
  ///
  /// Read off the tokens rather than off the `Mutation` projection, because a projection is not a
  /// type this pass can inspect. An exchange written as a type of its own answers whatever its own
  /// `Response` is, and one that means *nothing* writes `Noop` — see the module note.
  fn answers_nothing(&self) -> bool {
    let syn::Type::Tuple(pair) = &self.ty else {
      return false;
    };
    matches!(
      pair.elems.iter().collect::<Vec<_>>().as_slice(),
      [_, syn::Type::Tuple(answer)] if answer.elems.is_empty()
    )
  }
}

/// A word the declaration MAY have written, as the option a renderer takes.
fn optional(word: Option<&syn::LitStr>) -> TokenStream {
  match word {
    Some(word) => quote!(::core::option::Option::Some(#word)),
    None => quote!(::core::option::Option::None),
  }
}