ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! What the wire face's expansion says, read off its tokens.
//!
//! Its BEHAVIOUR — that a handler runs, that a failure renders under its heading, that a success and
//! only a success is forwarded — is asserted where it can be run: `ingraph/tests/mutation_wire.rs`,
//! which builds a real schema over a real source. What is here is what a token stream can be read
//! for: which fields exist, what each one publishes, which signature the call is cast to, and the
//! ORDER of the six steps, that being the load-bearing part.

use super::super::tests::watch_ops;
use crate::mutation::{DeclaredError, ExchangeModel, HandlerModel, MutationModel};

/// The emitted tokens with every space taken out.
fn tokens(model: &MutationModel) -> String {
  model.emit().to_string().split_whitespace().collect()
}

/// The rendered expansion, formatted — what a failing claim prints.
fn rendered(model: &MutationModel) -> String {
  prettyplease::unparse(&syn::parse2(model.emit()).expect("the expansion parses as a file"))
}

/// The node with its wire word taken off — the same declaration, dressed for no wire at all.
fn bare() -> MutationModel {
  MutationModel {
    graphql: Vec::new(),
    ..watch_ops()
  }
}

/// A node with a `()` answer written as the pair's second half.
fn answering_nothing() -> MutationModel {
  MutationModel {
    exchanges: vec![ExchangeModel {
      field: syn::parse_quote!(reindex),
      ty: syn::parse_quote!((Reindex, ())),
      rename: None,
      handler: HandlerModel {
        path: syn::parse_quote!(crate::watch::reindex),
        awaited: false,
        context: Vec::new(),
        error: None,
      },
    }],
    ..watch_ops()
  }
}

/// NO WORD, NO FACE — a node with no `graphql(…)` still emits its whole Rust surface and nothing a
/// schema could read.
#[test]
fn a_node_dressed_for_no_wire_gets_no_face() {
  let model = bare();
  let emitted = tokens(&model);
  for absent in [
    "async_graphql",
    "if_async_graphql",
    "Object",
    "WatchOpsMutations",
  ] {
    assert!(!emitted.contains(absent), "{absent}: {}", rendered(&model));
  }
  // … and the declaration side is untouched by the absence.
  assert!(emitted.contains("pubenumWatchOpsCommand"), "{emitted}");
}

/// The unit is UNCONDITIONAL and the face rides the gate — a record's query unit's own split, so a
/// build without the binding still has the type an application mounts.
#[test]
fn the_unit_is_unconditional_and_the_face_is_gated() {
  let model = watch_ops();
  let emitted = tokens(&model);
  let gate = emitted
    .find("::ingraph::__private::gate::if_async_graphql!")
    .expect("the face rides the binding gate");
  let unit = emitted
    .find("pubstructWatchOpsMutations;")
    .expect("the unit is emitted");
  assert!(unit < gate, "the unit is outside the gate: {emitted}");
  assert!(
    emitted[gate..].contains("::ingraph::__private::async_graphql::Object"),
    "{}",
    rendered(&model)
  );
}

/// ONE ROOT FIELD PER EXCHANGE, published under its `rename` word or under the camelCase fallback the
/// record family already uses.
#[test]
fn every_exchange_is_its_own_root_field() {
  let model = watch_ops();
  let emitted = tokens(&model);
  for (method, published) in [
    ("__async_graphql_add", "addWatch"),
    ("__async_graphql_remove", "remove"),
    ("__async_graphql_reindex", "reindex"),
  ] {
    assert!(
      emitted.contains(&format!("#[graphql(name=\"{published}\")]asyncfn{method}")),
      "{published}: {}",
      rendered(&model)
    );
  }
}

/// EVERY resolver is `async fn` whatever its handler's face is — the wire's own shape, the awaited
/// axis living in whether the CALL is awaited.
#[test]
fn the_face_is_async_and_the_handler_decides_the_await() {
  let model = watch_ops();
  let emitted = tokens(&model);
  assert_eq!(emitted.matches("asyncfn__async_graphql_").count(), 3);
  // `add` is the declaration's one awaited handler …
  assert!(
    emitted.contains("WatchOps::__ingraph_exchange_add(::ingraph::__private::resource::Shared::<crate::Catalog>::get(__ingraph_granted_0),__async_graphql_input).await"),
    "{}",
    rendered(&model)
  );
  // … and the blocking ones are called inline.
  assert!(
    emitted.contains("WatchOps::__ingraph_exchange_remove(__async_graphql_input);"),
    "{}",
    rendered(&model)
  );
}

/// THE THREE-TIER CONTRACT is cast ONCE, in the node's own per-exchange call, and this resolver
/// spends that call rather than casting a second time.
///
/// The cast itself is asserted where it lives — `face`'s suite — and what matters here is the
/// property a second cast would have destroyed: a handler that does not wear the signature its
/// declaration chose is refused ONCE, at the `handler` word, however many faces the node publishes.
/// So the handler's own path appears in this whole expansion exactly once per exchange, and it is
/// not in a resolver.
#[test]
fn the_resolver_spends_the_one_cast_rather_than_making_a_second() {
  let model = watch_ops();
  let emitted = tokens(&model);
  for (handler, call) in [
    ("crate::watch::add(", "__ingraph_exchange_add"),
    ("crate::watch::remove(", "__ingraph_exchange_remove"),
    ("crate::watch::reindex(", "__ingraph_exchange_reindex"),
  ] {
    assert_eq!(
      emitted.matches(handler).count(),
      1,
      "{handler}: {}",
      rendered(&model)
    );
    let resolver = emitted
      .rsplit_once("if_async_graphql!")
      .expect("the gate")
      .1;
    assert!(
      !resolver.contains(handler),
      "the handler is named in the CALL and not in the resolver: {}",
      rendered(&model)
    );
    assert!(
      resolver.contains(&format!("WatchOps::{call}(")),
      "{call}: {}",
      rendered(&model)
    );
  }
}

/// THE ONE-CODE-HEAD LAW reaches the renderer as the option it is, and a canned failure hands the
/// declaration's own sentence rather than anything the handler carried.
#[test]
fn each_failure_renders_under_the_heading_its_declaration_wrote() {
  let model = watch_ops();
  let emitted = tokens(&model);
  assert!(
    emitted.contains(
      "::ingraph::__private::graphql::refused_exchange(::core::option::Option::Some(\"ADD_FAILED\"),&__ingraph_refusal)"
    ),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains(
      "::ingraph::__private::graphql::refused_exchange(::core::option::Option::Some(\"NOT_OURS\"),\"thatwatchisnotours\")"
    ),
    "{}",
    rendered(&model)
  );
}

/// THE ORDER, which is the module note's whole subject: the source's line is looked up FIRST, so a
/// schema that never mounted this node refuses with nothing done.
#[test]
fn the_line_is_found_before_anything_has_an_effect() {
  let model = watch_ops();
  let emitted = tokens(&model);
  let resolver = emitted
    .split_once("asyncfn__async_graphql_add")
    .expect("the first resolver")
    .1;
  let line = resolver.find("let__ingraph_line=").expect("the line");
  let grant = resolver.find("let__ingraph_granted_0=").expect("the grant");
  let mint = resolver.find("let__ingraph_command=").expect("the command");
  let call = resolver
    .find("WatchOps::__ingraph_exchange_add(")
    .expect("the handler's own call");
  let forward = resolver.find("say_async").expect("the forward");
  assert!(
    line < grant && grant < mint && mint < call && call < forward,
    "{}",
    rendered(&model)
  );
}

/// OK-ONLY: the forward is reached only past the match that returns on a failure, so a change that
/// did not happen is never applied.
#[test]
fn a_failure_returns_before_the_forward() {
  let model = watch_ops();
  let emitted = tokens(&model);
  let resolver = emitted
    .split_once("asyncfn__async_graphql_add")
    .expect("the first resolver")
    .1;
  let refusal = resolver
    .find("returnstatic::core::result::Result::Err")
    .or_else(|| resolver.find("::core::result::Result::Err(__ingraph_refusal)"))
    .expect("the failing arm");
  assert!(
    refusal < resolver.find("say_async").expect("the forward"),
    "{}",
    rendered(&model)
  );
}

/// THE COMMAND CARRIES WHAT WAS ASKED FOR, cloned before the handler spends the request.
#[test]
fn the_command_is_minted_from_a_clone_of_the_request() {
  let model = watch_ops();
  let emitted = tokens(&model);
  assert!(
    emitted.contains(
      "let__ingraph_command=WatchOpsCommand::Add(::core::clone::Clone::clone(&__async_graphql_input));"
    ),
    "{}",
    rendered(&model)
  );
}

/// A LINE THAT IS GONE is the transport's own refusal, at both of the two places it can be gone.
#[test]
fn an_absent_line_and_a_dead_one_are_one_refusal() {
  let model = watch_ops();
  let emitted = tokens(&model);
  assert_eq!(
    emitted
      .matches(
        "::ingraph::__private::graphql::refused(&::ingraph::__private::drive::QueryError::UnreachableSource)"
      )
      .count(),
    // Two per resolver — the lookup and the send — over three exchanges.
    6,
    "{}",
    rendered(&model)
  );
}

/// `()` ANSWERS AS `Boolean!`, and its own unit is read out rather than dropped.
#[test]
fn an_exchange_that_answers_nothing_publishes_a_boolean() {
  let model = answering_nothing();
  let emitted = tokens(&model);
  assert!(
    emitted.contains("->::ingraph::__private::async_graphql::Result<::core::primitive::bool>"),
    "{}",
    rendered(&model)
  );
  assert!(
    emitted.contains("let()=__ingraph_answer;::core::result::Result::Ok(true)"),
    "{}",
    rendered(&model)
  );
}

/// An exchange that answers SOMETHING answers its own `Response`, through the projection — and the
/// `Boolean!` road is taken by exactly the one field whose pair ends in `()`.
#[test]
fn an_exchange_that_answers_something_answers_its_own_response() {
  let model = watch_ops();
  let emitted = tokens(&model);
  assert!(
    emitted.contains(
      "->::ingraph::__private::async_graphql::Result<<(AddWatch,AddResponse)as::ingraph::__private::source::Mutation>::Response>"
    ),
    "{}",
    rendered(&model)
  );
  // `reindex` is the fixture's `(Reindex, ())`, so exactly one of the three takes the bool road.
  assert_eq!(
    emitted.matches("Result<::core::primitive::bool>").count(),
    1,
    "{}",
    rendered(&model)
  );
}

/// A handler granted NOTHING takes the request and nothing beside it — the `context` word omitted is
/// the signature with no context in it, rather than an empty one.
#[test]
fn an_ungranted_handler_takes_the_request_alone() {
  let model = answering_nothing();
  let emitted = tokens(&model);
  assert!(
    emitted.contains("WatchOps::__ingraph_exchange_reindex(__async_graphql_input)"),
    "{}",
    rendered(&model)
  );
  // The CALL takes the request alone too — the `context` word omitted is a signature with no
  // context in it rather than an empty one, at both ends.
  assert!(
    emitted.contains(
      "fn__ingraph_exchange_reindex(__ingraph_request:<(Reindex,())as::ingraph::__private::source::Mutation>::Request,)"
    ),
    "{}",
    rendered(&model)
  );
  assert!(!emitted.contains("__ingraph_granted_"), "{emitted}");
}

/// Every framework name goes through the shelf, and the async-graphql ATTRIBUTE carries the shelf as
/// its `crate` — without which the attribute itself does not resolve in a declaring crate.
#[test]
fn the_face_names_the_shelf_at_the_attribute_too() {
  let model = watch_ops();
  let emitted = tokens(&model);
  assert!(
    emitted.contains(
      "#[::ingraph::__private::async_graphql::Object(crate=\"::ingraph::__private::async_graphql\",name=\"WatchOpsMutations\")]"
    ),
    "{}",
    rendered(&model)
  );
}

/// A RENAMED crate moves every path the face writes, the vendored attribute path included.
#[test]
fn a_renamed_crate_moves_the_faces_paths() {
  let model = MutationModel {
    krate: syn::parse_quote!(other::ingraph),
    ..watch_ops()
  };
  let emitted = tokens(&model);
  assert!(
    emitted.contains("other::ingraph::__private::gate::if_async_graphql!"),
    "{emitted}"
  );
  assert!(
    emitted.contains("crate=\"other::ingraph::__private::async_graphql\""),
    "{emitted}"
  );
  // Nothing reaches the DEFAULT root. Asserted as *every occurrence of the shelf is preceded by the
  // renamed root*, because `other::ingraph::__private` contains the default spelling as a substring
  // and a bare `contains` would pass a face that named both.
  assert_eq!(
    emitted.matches("::ingraph::__private").count(),
    emitted.matches("other::ingraph::__private").count(),
    "{emitted}"
  );
}

/// The published word is the `rename` verbatim where one was written, and the record's own `None`
/// stays `None` — the convention lives in the binding and never in the record.
#[test]
fn the_published_word_is_the_bindings_decision() {
  let model = watch_ops();
  assert_eq!(model.exchanges[0].published(), "addWatch");
  assert_eq!(model.exchanges[1].published(), "remove");
  assert!(model.exchanges[0].rename.is_some());
  assert!(model.exchanges[1].rename.is_none());

  let cased = ExchangeModel {
    field: syn::parse_quote!(add_watch_root),
    ty: syn::parse_quote!((AddWatch, ())),
    rename: None,
    handler: HandlerModel {
      path: syn::parse_quote!(crate::add),
      awaited: false,
      context: Vec::new(),
      error: Some(DeclaredError::Canned {
        message: syn::parse_quote!("no"),
        code: None,
      }),
    },
  };
  assert_eq!(cased.published(), "addWatchRoot");
}