ingraph_codegen/mutation/wire.rs
1//! The MUTATION NODE's WIRE FACE: one root field per exchange, and the resolver behind each.
2//!
3//! ```text
4//! type Mutation {
5//! addWatch(input: AddWatchInput!): AddResponse! # WatchOpsMutations::__async_graphql_add
6//! remove(input: RemoveWatchInput!): Boolean! # … and a `()` answer is `Boolean!`
7//! reindex(input: ReindexInput!): Boolean!
8//! }
9//! ```
10//!
11//! # PER-FIELD, and the shape is what deleted a whole layer
12//!
13//! Every exchange is its own root field with its own handler, its own answer and its own declared
14//! failure. So there is no node-level request union, no node-level response union, and — the part
15//! that matters — NO WAY TO ANSWER THE WRONG COMMAND: the arm a runtime check used to look for is
16//! unwritable rather than guarded, because the field a client wrote IS the handler that runs.
17//!
18//! # WHAT A RESOLVER DOES, in the order it does it
19//!
20//! 1. **Find the source's line first.** `ctx.data::<Commands<…>>()` before anything else, so a schema
21//! that never mounted this node refuses with nothing done. This is the ordering that matters most
22//! in the whole file: every later step has an effect, and the one failure that cannot be hoisted
23//! is the source dying between the handler's answer and the forward.
24//! 2. **Take the grants**, in the order `context(resource("…"), …)` wrote them.
25//! 3. **Mint the command** from a CLONE of the request, before the handler spends it.
26//! 4. **Call the handler through the node's own per-exchange call**, which is where the three-tier
27//! contract is cast: that call binds the handler to the exact type the `error(…)` word chose, so
28//! a body that wears another signature is `E0308` at the `handler` path word rather than deep
29//! inside these tokens. It is emitted ONCE and spent by both faces — see
30//! [`face`](super::face), which states why a second cast here would report one mistake twice.
31//! 5. **Render a failure** under the heading its declaration wrote — the one-code-head law, which
32//! lives in [`refused_exchange`](../../../ingraph/fn.refused_exchange.html).
33//! 6. **Forward, ONE WAY and ONLY ON SUCCESS.** A change that failed has no living application, so
34//! nothing is sent; a change that succeeded is minted as its command variant and handed to the
35//! source's `Control` line, which never answers.
36//!
37//! # A DECLARED EXCHANGE'S REQUEST IS `Clone`, and the bound is the forward's
38//!
39//! Step 3 clones. That is a real requirement on every request type a declaration names, and it is
40//! enforced HERE — at the resolver — rather than at the declaration, so it is worth saying plainly
41//! what it costs and why it is the shape it is.
42//!
43//! The command carries the REQUEST (the record's own ruling: what travels to the living application
44//! is what was asked for) and the handler takes that request BY VALUE (the three-tier signature's
45//! own ruling). Two parties want one value, and one of them runs first, so a copy is made before the
46//! handler spends it.
47//!
48//! It costs a declaration almost nothing, and the reason is what a request already IS: a wire input
49//! object, which async-graphql's own `InputType` already requires be `Send + Sync + Sized` and which
50//! is by construction a bag of owned, decoded values with no borrow in it. `Clone` is the nature of
51//! such a thing rather than an imposition on it.
52//!
53//! The two alternatives were both worse and both contradict a ruling. Handing the handler
54//! `&Request` contradicts the signature the three tiers are cast to — and would make a handler
55//! unable to consume what it was given, which is what most of them want. Forwarding the RESPONSE
56//! instead contradicts what a command IS: the living application applies what was ASKED FOR, and a
57//! response is what came back.
58//!
59//! # The door is keyed by the COMMAND TYPE, and needs no wrapper
60//!
61//! [`SqlDoor`](../../../ingraph/graphql/struct.SqlDoor.html) exists because `ctx.data` is a lookup on
62//! a concrete type and a POOL is not one — two records over one database would collide. Nothing here
63//! has that problem: a node mints a command enum of its own, one node is one source's command face,
64//! so `Commands<WatchOpsCommand>` is already the precise key. An application installs it with
65//! `Schema::build(…).data(commands)` and the resolver reads it back.
66//!
67//! # `()` ANSWERS AS `Boolean!`, and the pair spelling is where that is read
68//!
69//! An exchange written `(Request, ())` says *it worked* and nothing else, and async-graphql has no
70//! `OutputType` for `()` — so the field publishes `Boolean!` and answers `true`. It is read off the
71//! PAIR, syntactically, because that is where the emission can see it: a field type is otherwise an
72//! opaque `Mutation` implementor whose `Response` this pass cannot inspect. An exchange written as a
73//! type of its own that answers nothing writes [`Noop`](../../../ingraph/struct.Noop.html) — the
74//! WIRE-level nothing, which exists precisely because a published position has to render.
75
76use proc_macro2::TokenStream;
77use quote::{format_ident, quote, quote_spanned};
78
79use super::{DeclaredError, ExchangeModel, MutationModel};
80use crate::{emit::wire::wire_member, method::wire_method};
81
82#[cfg(test)]
83mod tests;
84
85impl MutationModel {
86 /// The wire unit's name — the node's own, with `Mutations` after it.
87 ///
88 /// [`default_queries_name`](crate::model::default_queries_name)'s shape one family over, and
89 /// derived for its reason: the node's name IS the vocabulary's name, and a second word for it
90 /// would be a name two spellings could disagree about.
91 #[must_use]
92 pub fn unit_name(&self) -> syn::Ident {
93 format_ident!("{}Mutations", self.name)
94 }
95
96 /// The wire face, or nothing at all for a node with no `graphql(…)` word.
97 ///
98 /// TWO items, split exactly as a record's query unit is: the unit TYPE is unconditional and the
99 /// `#[Object]` face rides the binding gate. A build without the binding therefore still has the
100 /// type an application mounts, and what it does not have is a schema over it — which is the
101 /// honest shape, since the type is a name in somebody else's code and the face is this crate's.
102 pub(super) fn wire(&self) -> TokenStream {
103 if self.graphql.is_empty() {
104 return TokenStream::new();
105 }
106 let unit = self.unit();
107 let face = self.face();
108 quote! {
109 #unit
110 #face
111 }
112 }
113
114 /// The mountable UNIT: an empty type whose `#[Object]` face carries this node's root fields.
115 ///
116 /// The `#[Object]` cannot go on the node itself, and the reason is structural rather than
117 /// stylistic: a resolver is a method on a VALUE, a schema is built from a `Default`, and a mutation
118 /// node's fields are exchange types nobody constructs. The node is a declaration vehicle; this is
119 /// the thing a root folds.
120 fn unit(&self) -> TokenStream {
121 let vis = &self.vis;
122 let name = self.unit_name();
123 let node = &self.name;
124 let doc = crate::emit::leading(&format!(
125 "The root fields a [`{node}`] answers — one per exchange it declared.\n\nMounted by folding \
126 it into a graph's root mutation; it holds nothing, and it reaches the source it controls \
127 through the command line the schema was built with."
128 ));
129 quote! {
130 #[doc = #doc]
131 #[derive(
132 ::core::fmt::Debug,
133 ::core::clone::Clone,
134 ::core::marker::Copy,
135 ::core::default::Default,
136 )]
137 #vis struct #name;
138 }
139 }
140
141 /// The `#[Object]` over every exchange, inside the binding gate.
142 fn face(&self) -> TokenStream {
143 let krate = &self.krate;
144 let name = self.unit_name();
145 let sdl = name.to_string();
146 let ag = crate::emit::framework(krate, &[], "async_graphql");
147 let shelf = crate::emit::vendored(krate, "async_graphql");
148 let gate = crate::emit::framework(krate, &["gate"], "if_async_graphql");
149 let prelude = crate::emit::wire::prelude();
150 let fields = self
151 .exchanges
152 .iter()
153 .map(|exchange| self.resolver(exchange));
154 quote! {
155 #gate! {
156 const _: () = {
157 #prelude
158
159 #[#ag::Object(crate = #shelf, name = #sdl)]
160 impl #name {
161 #(#fields)*
162 }
163 };
164 }
165 }
166 }
167
168 /// ONE EXCHANGE's resolver — see the module note for the order of what it does.
169 #[expect(
170 clippy::too_many_lines,
171 reason = "one resolver is one statement list, and the six steps the module note tabulates are \
172 exactly the six blocks below — splitting them into helpers would move the ORDER, \
173 which is the load-bearing part, out of the one place it can be read"
174 )]
175 fn resolver(&self, exchange: &ExchangeModel) -> TokenStream {
176 let krate = &self.krate;
177 let ag = crate::emit::framework(krate, &[], "async_graphql");
178 let mutation = crate::emit::framework(krate, &["source"], "Mutation");
179 let node = crate::emit::framework(krate, &["source"], "MutationNode");
180 let commands = crate::emit::framework(krate, &["source"], "Commands");
181 let shared = crate::emit::framework(krate, &["resource"], "Shared");
182 let refused = crate::emit::framework(krate, &["graphql"], "refused");
183 let refused_exchange = crate::emit::framework(krate, &["graphql"], "refused_exchange");
184 let unreachable = crate::emit::framework(krate, &["drive"], "QueryError");
185
186 let ty = &exchange.ty;
187 let name = &self.name;
188 let command = self.command_name();
189 let variant = exchange.variant();
190 let field = exchange.published();
191 let method = wire_method(&format_ident!("{}", exchange.named()));
192 let ctx = wire_method(&format_ident!("ctx"));
193 let input = wire_method(&format_ident!("input"));
194
195 let request = quote!(<#ty as #mutation>::Request);
196 // The RESPONSE, and the one place a `()` answer is read: the pair spelling is where this pass
197 // can see it, per the module note.
198 let unit_answer = exchange.answers_nothing();
199 let response = if unit_answer {
200 quote!(::core::primitive::bool)
201 } else {
202 quote!(<#ty as #mutation>::Response)
203 };
204
205 // THE LINE, first — a schema that never mounted this node refuses with nothing done.
206 let line = quote! {
207 let __ingraph_line = #ag::Context::data::<#commands<<#name as #node>::Command>>(#ctx)
208 .map_err(|_| #refused(&#unreachable::UnreachableSource))?;
209 };
210
211 // THE GRANTS, in the order the declaration wrote them, and nothing at all where it wrote none.
212 let granted: Vec<syn::Ident> = (0..exchange.handler.context.len())
213 .map(|at| format_ident!("__ingraph_granted_{at}"))
214 .collect();
215 let grants = exchange
216 .handler
217 .context
218 .iter()
219 .zip(&granted)
220 .map(|(resource, held)| {
221 quote! {
222 let #held = #ag::Context::data::<#shared<#resource>>(#ctx)?;
223 }
224 });
225 let arguments = granted
226 .iter()
227 .zip(&exchange.handler.context)
228 .map(|(held, resource)| quote!(#shared::<#resource>::get(#held)));
229
230 // THE COMMAND, minted BEFORE the handler spends the request — the forward carries what was
231 // asked for, and the handler takes it by value.
232 let at = exchange.field.span();
233 let clone = quote_spanned!(at=> ::core::clone::Clone::clone(&#input));
234 // The VARIANT is named on the enum itself and not through `<Node as MutationNode>::Command`,
235 // which the LINE above does spell: a projection is a type and a variant is resolved off a type
236 // PATH, so the two positions take the two spellings — the type one proving the row exists, the
237 // constructor one naming the enum this same expansion minted a line earlier.
238 let minted = quote! {
239 let __ingraph_command = #command::#variant(#clone);
240 };
241
242 // THE CALL, through the node's OWN per-exchange call — the one place the three-tier signature
243 // is cast, and it is spent here and by the assembled face. So a body that does not wear the
244 // signature its declaration chose is refused ONCE, at the `handler` path word, however many
245 // faces the node happens to publish.
246 let path = &exchange.handler.path;
247 let called = exchange.call_name();
248 let awaited = exchange.handler.awaited.then(|| quote!(.await));
249 let call = quote! {
250 #name::#called(#(#arguments,)* #input) #awaited
251 };
252 let (outcome, answer) = match &exchange.handler.error {
253 None => (
254 quote! {
255 let __ingraph_answer = #call;
256 },
257 quote!(__ingraph_answer),
258 ),
259 Some(declared) => {
260 let render = match declared {
261 DeclaredError::Rich { code, .. } => {
262 let code = optional(code.as_ref());
263 quote!(#refused_exchange(#code, &__ingraph_refusal))
264 }
265 DeclaredError::Canned { message, code } => {
266 let code = optional(code.as_ref());
267 quote! {{
268 // The canned failure's whole content is the DECLARATION's, so the handler's own
269 // `Err(())` is read for its POSITION and nothing else.
270 let () = __ingraph_refusal;
271 #refused_exchange(#code, #message)
272 }}
273 }
274 };
275 (
276 quote! {
277 let __ingraph_outcome = #call;
278 let __ingraph_answer = match __ingraph_outcome {
279 ::core::result::Result::Ok(__ingraph_answer) => __ingraph_answer,
280 ::core::result::Result::Err(__ingraph_refusal) => {
281 return ::core::result::Result::Err(#render);
282 }
283 };
284 },
285 quote!(__ingraph_answer),
286 )
287 }
288 };
289
290 // THE ANSWER: an exchange that says only *it worked* answers `true`, and its own `()` is read
291 // out through an irrefutable pattern so the binding is spent rather than merely dropped.
292 let answered = if unit_answer {
293 quote! {
294 let () = #answer;
295 ::core::result::Result::Ok(true)
296 }
297 } else {
298 quote!(::core::result::Result::Ok(#answer))
299 };
300
301 let doc = crate::emit::leading(&format!(
302 "The `{field}` exchange — validated and answered by `{handler}`, then applied by the source \
303 this node controls.",
304 handler = quote!(#path).to_string().replace(' ', ""),
305 ));
306 quote! {
307 #[doc = #doc]
308 #[graphql(name = #field)]
309 async fn #method(
310 &self,
311 #ctx: &#ag::Context<'_>,
312 #[graphql(name = "input")] #input: #request,
313 ) -> #ag::Result<#response> {
314 #line
315 #(#grants)*
316 #minted
317 #outcome
318 // ONE WAY, and only on success: the answer was already given, and what travels here is the
319 // change to APPLY. A source eats it and never replies.
320 if #commands::say_async(__ingraph_line, __ingraph_command).await.is_err() {
321 return ::core::result::Result::Err(#refused(&#unreachable::UnreachableSource));
322 }
323 #answered
324 }
325 }
326 }
327}
328
329impl ExchangeModel {
330 /// What the wire publishes this exchange as: its `rename = "…"` word, or its field name with a
331 /// lower-case initial.
332 ///
333 /// The convention lives HERE and not in the declaration record, which answers `None` for an
334 /// unrenamed field on purpose — what an unrenamed field is PUBLISHED as is the binding's decision,
335 /// and the record putting its own guess there would be the record deciding it.
336 ///
337 /// The fallback is [`wire_member`], which is the crate's ONE answer to *what a client sees where
338 /// nothing was written* — the same camelCase the record family's own faces fall back on, read from
339 /// the same function, so a mutation field and a record field never come to disagree about it.
340 #[must_use]
341 pub fn published(&self) -> String {
342 match &self.rename {
343 Some(rename) => rename.value(),
344 None => wire_member(&self.field),
345 }
346 }
347
348 /// Whether this exchange answers NOTHING — the `(Request, ())` pair, and only that.
349 ///
350 /// Read off the tokens rather than off the `Mutation` projection, because a projection is not a
351 /// type this pass can inspect. An exchange written as a type of its own answers whatever its own
352 /// `Response` is, and one that means *nothing* writes `Noop` — see the module note.
353 fn answers_nothing(&self) -> bool {
354 let syn::Type::Tuple(pair) = &self.ty else {
355 return false;
356 };
357 matches!(
358 pair.elems.iter().collect::<Vec<_>>().as_slice(),
359 [_, syn::Type::Tuple(answer)] if answer.elems.is_empty()
360 )
361 }
362}
363
364/// A word the declaration MAY have written, as the option a renderer takes.
365fn optional(word: Option<&syn::LitStr>) -> TokenStream {
366 match word {
367 Some(word) => quote!(::core::option::Option::Some(#word)),
368 None => quote!(::core::option::Option::None),
369 }
370}