Skip to main content

ingraph_codegen/mutation/
face.rs

1//! The MUTATION NODE's ASSEMBLED FACE: one function that is the whole of what a node can be told,
2//! and the two sums that are what it answers with.
3//!
4//! ```ignore
5//! impl WatchOps {
6//!   async fn handle_watch_ops(
7//!     catalog: &crate::Catalog,
8//!     cmd: WatchOpsCommand,
9//!   ) -> Result<WatchOpsResponse, WatchOpsError>;
10//! }
11//! ```
12//!
13//! # THE MODE IS THE OR OF ITS HANDLERS', which is what `ALL_SYNC` was recorded for
14//!
15//! A node whose every handler is blocking assembles into a BLOCKING function, and one awaited
16//! handler makes the whole face awaited. So a deployment that controls a wholly synchronous node
17//! needs no runtime to say anything to it — which is the dividend, and the reason the law is an OR
18//! rather than *always async*: an awaited face is the more general shape and the more expensive one,
19//! and paying for it where nothing awaits would be the framework choosing a runtime on an
20//! application's behalf.
21//!
22//! | the node's handlers | `ALL_SYNC` | the assembled face |
23//! |---|---|---|
24//! | every one blocking | `true` | `fn handle_…` |
25//! | at least one awaited | `false` | `async fn handle_…` |
26//!
27//! # IT IS THE TOTAL CAPABILITY, and the WIRE stays per-field
28//!
29//! The binding emits one root field per exchange and calls that exchange's own handler — the shape
30//! that makes *answering the wrong command* unwritable rather than guarded. Nothing about that
31//! changes here, and the two sums below never appear in a schema. What this face is for is every
32//! OTHER caller of a node: a first-party RPC or framework binding that has a command in hand and
33//! wants one door, a test that drives a node without a schema, and the source-side caller that holds
34//! a `<Node>Command` off its own `Control` line and wants to run it.
35//!
36//! So the node-level `Response` and `Error` sums — retired from the wire face, where per-field
37//! answering deleted them — are REVIVED here as this face's return vocabulary. They are the same
38//! types the retirement ledger named, in the one position that still has a use for them.
39//!
40//! # THE ERROR SUM IS HONESTLY EMPTY, and that is a real answer
41//!
42//! An arm per FALLIBLE exchange and none for the others: a `Never`-tier exchange contributes no way
43//! to fail, so a node whose every exchange is that tier gets an error sum with no variants at all.
44//! `Result<_, WatchOpsError>` is then a `Result` whose `Err` has no values — the same claim `()`'s
45//! `Infallible` command makes one seat over, and the same total-capability-and-honest-empty pattern.
46//!
47//! # ONE CALL SITE CASTS THE THREE-TIER SIGNATURE, and both faces spend it
48//!
49//! Each exchange gets a hidden [`ExchangeModel::call_name`] function on the node — the ONE place a
50//! handler is called at the exact signature its `error(…)` word chose, spanned at the `handler` path
51//! word. The wire's resolver calls it, and so does the arm of this face.
52//!
53//! A second, independent cast would have been the obvious way to write this face, and it is the one
54//! thing this module must not do: a handler whose body does not match its declaration would then be
55//! reported TWICE, at two sites, about one mistake — and the corpus that pins *the refusal lands on
56//! the word that chose it* would be pinning it twice over. One fact, one account.
57
58use proc_macro2::TokenStream;
59use quote::{ToTokens as _, format_ident, quote, quote_spanned};
60use syn::spanned::Spanned as _;
61
62use super::{DeclaredError, ExchangeModel, MutationModel};
63
64#[cfg(test)]
65mod tests;
66
67impl MutationModel {
68  /// The response sum's name — the node's own, with `Response` after it.
69  ///
70  /// Derived rather than declared, for [`command_name`](Self::command_name)'s reason: the node's
71  /// name IS the vocabulary's name, and a second word for it would be a name two spellings could
72  /// disagree about.
73  #[must_use]
74  pub fn response_name(&self) -> syn::Ident {
75    format_ident!("{}Response", self.name)
76  }
77
78  /// The error sum's name — the node's own, with `Error` after it.
79  #[must_use]
80  pub fn error_name(&self) -> syn::Ident {
81    format_ident!("{}Error", self.name)
82  }
83
84  /// The assembled face's name — `handle_` and the node's own name in snake case.
85  ///
86  /// Named after the NODE and not numbered, which is the ruling: a position in a list is a name that
87  /// moves when the list is reordered, and the node is what the face is the capability of.
88  #[must_use]
89  pub fn face_name(&self) -> syn::Ident {
90    format_ident!("handle_{}", crate::emit::snake(&self.name.to_string()))
91  }
92
93  /// Whether the assembled face is awaited — the OR law, read off the declaration.
94  #[must_use]
95  pub fn awaited(&self) -> bool {
96    !self.all_sync()
97  }
98
99  /// The whole assembled surface: the two sums, the per-exchange calls, and the face over them.
100  pub(super) fn assembly(&self) -> TokenStream {
101    let response = self.response();
102    let error = self.error();
103    let rendering = self.rendering();
104    let calls = self.calls();
105    let assembled = self.assembled();
106    quote! {
107      #response
108      #error
109      #rendering
110      #calls
111      #assembled
112    }
113  }
114
115  /// THE RESPONSE SUM: one arm per exchange, carrying that exchange's own answer.
116  ///
117  /// The payload is the PROJECTION `<Ty as Mutation>::Response`, exactly as the command enum's is a
118  /// projection of `Request` — so this emission is the same assert one seat over, and a `()` answer
119  /// is a `()` payload. The wire's `Boolean!` rendering has no business here: that is a RENDERING
120  /// for a schema position that must publish something, and this face answers in Rust.
121  fn response(&self) -> TokenStream {
122    let krate = &self.krate;
123    let vis = &self.vis;
124    let name = self.response_name();
125    let arms = self.exchanges.iter().map(|exchange| {
126      let variant = exchange.variant();
127      let ty = &exchange.ty;
128      let doc = crate::emit::leading(&format!(
129        "What the `{field}` exchange answered.",
130        field = exchange.named(),
131      ));
132      quote! {
133        #[doc = #doc]
134        #variant(<#ty as #krate::__private::source::Mutation>::Response)
135      }
136    });
137    let doc = crate::emit::leading(&format!(
138      "What [`{node}`]'s assembled face answers with — one arm per exchange it declared.\n\nThe \
139       node-level response sum, revived: the WIRE answers per field and never through this type, \
140       and what it serves is every other caller of \
141       [`{node}::{face}`]({node}::{face}).",
142      node = self.name,
143      face = self.face_name(),
144    ));
145    // PAYLOAD-BLIND, for the reason the error sum's own is: a derive would put a `Debug` bound on
146    // every declared response type, and the origin layer's discipline is *arity and never the
147    // payload*. It is written at all — where the COMMAND enum has none — because this is what comes
148    // BACK: a caller already holds what it sent, and what it is handed is what it inspects.
149    let debugged = self.exchanges.iter().map(|exchange| {
150      let variant = exchange.variant();
151      let printed = variant.to_string();
152      quote!(Self::#variant(_) => ::core::fmt::Formatter::write_str(__ingraph_f, #printed))
153    });
154    let debug = if self.exchanges.is_empty() {
155      quote!(match *self {})
156    } else {
157      quote!(match self { #(#debugged,)* })
158    };
159    quote! {
160      #[doc = #doc]
161      #vis enum #name {
162        #(#arms),*
163      }
164
165      impl ::core::fmt::Debug for #name {
166        fn fmt(&self, __ingraph_f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
167          #debug
168        }
169      }
170    }
171  }
172
173  /// THE ERROR SUM: one arm per FALLIBLE exchange, and none at all for a node that cannot fail.
174  ///
175  /// A `Rich` exchange's arm carries the type its declaration named; a `Canned` one carries nothing,
176  /// because a canned failure's whole content — the sentence and the heading — lives in the
177  /// declaration and the handler reports only the position it failed at.
178  fn error(&self) -> TokenStream {
179    let vis = &self.vis;
180    let name = self.error_name();
181    let arms = self.fallible().map(|exchange| {
182      let variant = exchange.variant();
183      let doc = crate::emit::leading(&format!(
184        "The `{field}` exchange refused.",
185        field = exchange.named(),
186      ));
187      let payload = match &exchange.handler.error {
188        Some(DeclaredError::Rich { ty, .. }) => quote!((#ty)),
189        // A canned failure carries no value: `Err(())` is a POSITION, and the words are the
190        // declaration's — which is what the `Display` below renders.
191        _ => TokenStream::new(),
192      };
193      quote! {
194        #[doc = #doc]
195        #variant #payload
196      }
197    });
198    let doc = crate::emit::leading(&format!(
199      "How [`{node}`]'s assembled face refuses — one arm per exchange that declared a failure.\n\nA \
200       node whose every exchange is the `Never` tier gets an enum with NO variants, which is the \
201       honest answer rather than an omission: there is no way for such a node to fail, so there is \
202       no value of this type.",
203      node = self.name,
204    ));
205    quote! {
206      #[doc = #doc]
207      #vis enum #name {
208        #(#arms),*
209      }
210    }
211  }
212
213  /// The error sum's own faces: what it prints, what it debugs as, that it IS an error, and the
214  /// heading its declaration wrote.
215  ///
216  /// # `Display` is the ONE-CODE-HEAD LAW, spelled here as the binding spells it
217  ///
218  /// A declared `code` heads the rendering and the failure's own words follow it, which is exactly
219  /// what `refused_exchange` does at the wire. So the same failure reads the same way through either
220  /// face — and a declaration that heads a failure whose own `Display` already carries a heading
221  /// publishes two, which is why the `code` word is omitted for such a type. See the macro's own doc.
222  ///
223  /// # `Debug` is HAND-WRITTEN and payload-blind, which is what keeps it free
224  ///
225  /// A derive would put a `Debug` bound on every declared error type. The origin layer's own debug
226  /// discipline is *arity and never the payload* — the same reason the command enum derives nothing
227  /// — so the arm's NAME is printed and the value inside it is reached by matching. The one bound
228  /// this whole emission does place is `Display` on a `Rich` failure, and that one the `code` word
229  /// already presupposed: a heading heads something a reader can read.
230  fn rendering(&self) -> TokenStream {
231    let name = self.error_name();
232    let empty = self.fallible().next().is_none();
233    // An UNINHABITED sum is matched through the place rather than through arms: there is no value,
234    // so there is no arm to write, and `match *self {}` is the compiler's own proof of it.
235    let (display, debug, code) = if empty {
236      (
237        quote!(match *self {}),
238        quote!(match *self {}),
239        quote!(match *self {}),
240      )
241    } else {
242      let displayed = self.fallible().map(|exchange| exchange.displayed());
243      let debugged = self.fallible().map(|exchange| {
244        let variant = exchange.variant();
245        let printed = variant.to_string();
246        let bound = exchange.binds_a_payload().then(|| quote!((_)));
247        quote!(Self::#variant #bound => ::core::fmt::Formatter::write_str(__ingraph_f, #printed))
248      });
249      let coded = self.fallible().map(|exchange| {
250        let variant = exchange.variant();
251        let bound = exchange.binds_a_payload().then(|| quote!((_)));
252        let word = match exchange.declared_code() {
253          Some(code) => quote!(::core::option::Option::Some(#code)),
254          None => quote!(::core::option::Option::None),
255        };
256        quote!(Self::#variant #bound => #word)
257      });
258      (
259        quote!(match self { #(#displayed,)* }),
260        quote!(match self { #(#debugged,)* }),
261        quote!(match self { #(#coded,)* }),
262      )
263    };
264    let doc = crate::emit::leading(
265      "The heading this failure renders under, where its declaration wrote a `code` word.\n\nThe \
266       same fact `Fallibility::code` carries in the declaration record, reachable from the value \
267       itself — which is what a caller mapping this sum onto a transport's own vocabulary needs.",
268    );
269    quote! {
270      impl ::core::fmt::Display for #name {
271        fn fmt(&self, __ingraph_f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
272          #display
273        }
274      }
275
276      impl ::core::fmt::Debug for #name {
277        fn fmt(&self, __ingraph_f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
278          #debug
279        }
280      }
281
282      impl ::core::error::Error for #name {}
283
284      impl #name {
285        #[doc = #doc]
286        #[must_use]
287        pub const fn code(&self) -> ::core::option::Option<&'static str> {
288          #code
289        }
290      }
291    }
292  }
293
294  /// THE ONE CAST SITE per exchange — see the module note for why there is exactly one.
295  fn calls(&self) -> TokenStream {
296    let name = &self.name;
297    let calls = self.exchanges.iter().map(|exchange| exchange.call(self));
298    quote! {
299      impl #name {
300        #(#calls)*
301      }
302    }
303  }
304
305  /// THE ASSEMBLED FACE itself: the grants its exchanges were granted, the command, and the two sums.
306  fn assembled(&self) -> TokenStream {
307    let vis = &self.vis;
308    let name = &self.name;
309    let face = self.face_name();
310    let command = self.command_name();
311    let response = self.response_name();
312    let error = self.error_name();
313    let granted = self.granted();
314    let parameters = granted
315      .iter()
316      .map(|(held, resource)| quote!(#held: &#resource));
317    let awaited = self.awaited().then(|| quote!(async));
318    let arms = self
319      .exchanges
320      .iter()
321      .map(|exchange| exchange.arm(self, &granted));
322    // An UNINHABITED command is matched through the place, exactly as the empty error sum is: a node
323    // that declared no exchange has nothing that can be said to it, and no arm to write.
324    let body = if self.exchanges.is_empty() {
325      quote!(match __ingraph_cmd {})
326    } else {
327      quote!(match __ingraph_cmd { #(#arms)* })
328    };
329    let doc = crate::emit::leading(&format!(
330      "Run whatever this node was told — [`{node}`]'s TOTAL CAPABILITY, in one \
331       {face_kind}function.\n\nOne arm per declared exchange, each calling that exchange's own \
332       handler at the signature its `error(…)` word chose. The face is {face_kind}because \
333       `ALL_SYNC` is `{all_sync}` — the OR law: a node whose every handler is blocking assembles \
334       into a blocking function, and one awaited handler makes the whole face awaited.\n\nThe WIRE \
335       does not come through here. A schema publishes one root field per exchange and calls that \
336       exchange's handler directly; what this serves is every other caller — a first-party \
337       transport, a test, and the source-side party holding a command off its own `Control` \
338       line.\n\n# Errors\n\nWhichever of [`{error}`]({error})'s arms the exchange that ran declared.",
339      node = self.name,
340      face_kind = if self.awaited() {
341        "awaited "
342      } else {
343        "blocking "
344      },
345      all_sync = self.all_sync(),
346    ));
347    quote! {
348      impl #name {
349        #[doc = #doc]
350        #vis #awaited fn #face(
351          #(#parameters,)*
352          __ingraph_cmd: #command,
353        ) -> ::core::result::Result<#response, #error> {
354          #body
355        }
356      }
357    }
358  }
359
360  /// Every exchange that declared a failure, in declaration order — the error sum's arms.
361  fn fallible(&self) -> impl Iterator<Item = &ExchangeModel> {
362    self
363      .exchanges
364      .iter()
365      .filter(|exchange| exchange.handler.error.is_some())
366  }
367
368  /// The RESOURCES this node's handlers were granted, deduplicated, in first-written order — the
369  /// assembled face's own parameter list.
370  ///
371  /// One face runs every exchange, so it is handed the UNION of what they were granted: a caller
372  /// holding a command does not know which arm it will take, and a signature that varied by arm
373  /// would not be one function.
374  ///
375  /// The key is the path AS WRITTEN. Two spellings of one type — an alias, a re-export — are two
376  /// parameters here, which is the honest answer for a pass that resolves nothing: this emission
377  /// cannot know they meet, and guessing that they do would be it deciding a question the compiler
378  /// owns.
379  fn granted(&self) -> Vec<(syn::Ident, syn::Path)> {
380    // `cmd` is seeded, so a resource whose name would collide with the command parameter takes the
381    // suffixed spelling instead of shadowing it.
382    let mut taken: Vec<String> = vec!["cmd".to_owned()];
383    let mut granted: Vec<(syn::Ident, syn::Path)> = Vec::new();
384    for resource in self
385      .exchanges
386      .iter()
387      .flat_map(|exchange| &exchange.handler.context)
388    {
389      if granted
390        .iter()
391        .any(|(_, held)| super::path_word(held) == super::path_word(resource))
392      {
393        continue;
394      }
395      let bare = resource.segments.last().map_or_else(
396        || "granted".to_owned(),
397        |segment| crate::emit::snake(&segment.ident.to_string()),
398      );
399      let mut held = bare.clone();
400      let mut at = 1;
401      while taken.contains(&held) {
402        held = format!("{bare}_{at}");
403        at += 1;
404      }
405      taken.push(held.clone());
406      granted.push((format_ident!("{held}"), resource.clone()));
407    }
408    granted
409  }
410}
411
412impl ExchangeModel {
413  /// The hidden function that CALLS this exchange's handler — the one place its three-tier signature
414  /// is cast.
415  #[must_use]
416  pub fn call_name(&self) -> syn::Ident {
417    format_ident!("__ingraph_exchange_{}", self.named())
418  }
419
420  /// Whether this exchange's error-sum arm carries a value — `Rich` and nothing else.
421  fn binds_a_payload(&self) -> bool {
422    matches!(&self.handler.error, Some(DeclaredError::Rich { .. }))
423  }
424
425  /// The `code = "…"` word this exchange's failure was headed with, where one was written.
426  fn declared_code(&self) -> Option<&syn::LitStr> {
427    match &self.handler.error {
428      Some(DeclaredError::Rich { code, .. } | DeclaredError::Canned { code, .. }) => code.as_ref(),
429      None => None,
430    }
431  }
432
433  /// This exchange's arm of the error sum's `Display` — the one-code-head law, one arm at a time.
434  fn displayed(&self) -> TokenStream {
435    let variant = self.variant();
436    let head = self.declared_code().map(|code| {
437      let head = format!("{code}: ", code = code.value());
438      quote!(::core::fmt::Formatter::write_str(__ingraph_f, #head)?;)
439    });
440    match &self.handler.error {
441      // The RICH failure's words are the value's own, so the heading is written and the value
442      // renders itself — which is exactly what the wire's own renderer does with the same pair.
443      Some(DeclaredError::Rich { .. }) => quote! {
444        Self::#variant(__ingraph_refusal) => {
445          #head
446          ::core::fmt::Display::fmt(__ingraph_refusal, __ingraph_f)
447        }
448      },
449      // The CANNED failure's whole rendering is fixed at the declaration, so it is ONE literal:
450      // there is nothing at runtime that could vary it.
451      Some(DeclaredError::Canned { message, code }) => {
452        let sentence = match code {
453          Some(code) => format!(
454            "{code}: {message}",
455            code = code.value(),
456            message = message.value()
457          ),
458          None => message.value(),
459        };
460        quote!(Self::#variant => ::core::fmt::Formatter::write_str(__ingraph_f, #sentence))
461      }
462      None => TokenStream::new(),
463    }
464  }
465
466  /// The hidden call — this exchange's handler, at the exact signature its declaration chose.
467  ///
468  /// The CAST is a `let` with the tier written on it rather than the function's return type alone,
469  /// and the difference is the diagnostic: an annotated binding reports a mismatched body at the
470  /// call — which is spanned at the `handler` path word — and says *expected `…`, found `…`* about
471  /// the two types the declaration and the body disagree on.
472  fn call(&self, model: &MutationModel) -> TokenStream {
473    let krate = &model.krate;
474    let mutation = crate::emit::framework(krate, &["source"], "Mutation");
475    let ty = &self.ty;
476    let name = self.call_name();
477    let path = &self.handler.path;
478
479    let granted: Vec<syn::Ident> = (0..self.handler.context.len())
480      .map(|at| format_ident!("__ingraph_granted_{at}"))
481      .collect();
482    let parameters = granted
483      .iter()
484      .zip(&self.handler.context)
485      .map(|(held, resource)| quote!(#held: &#resource));
486    let awaited = self.handler.awaited.then(|| quote!(.await));
487    let face = self.handler.awaited.then(|| quote!(async));
488    let call = quote_spanned! {path.span()=>
489      #path(#(#granted,)* __ingraph_request) #awaited
490    };
491
492    let tier = match &self.handler.error {
493      None => quote!(<#ty as #mutation>::Response),
494      Some(DeclaredError::Rich { ty: failure, .. }) => {
495        let failure = failure.to_token_stream();
496        quote!(::core::result::Result<<#ty as #mutation>::Response, #failure>)
497      }
498      Some(DeclaredError::Canned { .. }) => {
499        quote!(::core::result::Result<<#ty as #mutation>::Response, ()>)
500      }
501    };
502    let doc = crate::emit::leading(&format!(
503      "The `{field}` exchange's handler, called at the signature its declaration chose.\n\nHidden, \
504       and there is exactly ONE of it: the wire's resolver and the assembled face both spend this \
505       call, so a body that wears another signature is refused once, at the `handler` word.",
506      field = self.named(),
507    ));
508    quote! {
509      #[doc = #doc]
510      #[doc(hidden)]
511      #face fn #name(
512        #(#parameters,)*
513        __ingraph_request: <#ty as #mutation>::Request,
514      ) -> #tier {
515        let __ingraph_outcome: #tier = #call;
516        __ingraph_outcome
517      }
518    }
519  }
520
521  /// This exchange's arm of the assembled face.
522  fn arm(&self, model: &MutationModel, granted: &[(syn::Ident, syn::Path)]) -> TokenStream {
523    let command = model.command_name();
524    let response = model.response_name();
525    let error = model.error_name();
526    let variant = self.variant();
527    let call = self.call_name();
528    // The grants this exchange asked for, taken out of the face's own parameters BY THE PATH THAT
529    // NAMED THEM — the same key the union was built under.
530    let arguments = self.handler.context.iter().map(|resource| {
531      granted
532        .iter()
533        .find(|(_, held)| super::path_word(held) == super::path_word(resource))
534        .map_or_else(|| quote!(#resource), |(held, _)| quote!(#held))
535    });
536    let awaited = self.handler.awaited.then(|| quote!(.await));
537    let ran = quote!(Self::#call(#(#arguments,)* __ingraph_request) #awaited);
538
539    match &self.handler.error {
540      None => quote! {
541        #command::#variant(__ingraph_request) => ::core::result::Result::Ok(
542          #response::#variant(#ran)
543        ),
544      },
545      Some(DeclaredError::Rich { .. }) => quote! {
546        #command::#variant(__ingraph_request) => match #ran {
547          ::core::result::Result::Ok(__ingraph_answer) =>
548            ::core::result::Result::Ok(#response::#variant(__ingraph_answer)),
549          ::core::result::Result::Err(__ingraph_refusal) =>
550            ::core::result::Result::Err(#error::#variant(__ingraph_refusal)),
551        },
552      },
553      Some(DeclaredError::Canned { .. }) => quote! {
554        #command::#variant(__ingraph_request) => match #ran {
555          ::core::result::Result::Ok(__ingraph_answer) =>
556            ::core::result::Result::Ok(#response::#variant(__ingraph_answer)),
557          // The canned failure's `Err(())` is read for its POSITION and nothing else — the words are
558          // the declaration's, and the arm below is where they are rendered from.
559          ::core::result::Result::Err(()) =>
560            ::core::result::Result::Err(#error::#variant),
561        },
562      },
563    }
564  }
565}