ingraph_codegen/catalog.rs
1//! THE ROOT CATALOG's resource half: the fields a graph root marks `#[ingraph(resource)]`, what a
2//! deployment configures them through, and the walk that declares them.
3//!
4//! ```ignore
5//! #[ingraph::graph]
6//! pub struct Media {
7//! videos: Video,
8//! #[ingraph(resource)]
9//! egemma: Egemma,
10//! #[ingraph(resource(factory))]
11//! pool: Pool,
12//! #[ingraph(resource(factory = "crate::boot::cache"))]
13//! cache: Cache,
14//! #[ingraph(resource(factory = "crate::boot::index", teardown))]
15//! index: Index,
16//! }
17//! ```
18//!
19//! # ONE namespace, and the field spells the THING
20//!
21//! A root's fields are the deployment's whole catalog — nodes and resources together — so a
22//! resource is written exactly as a node is, the TYPE in the field and the kind in the attribute.
23//! Nothing here mints a name: the mount IS the field's identifier, and two members that would
24//! collide collide as two Rust fields, which is a refusal this emission does not have to write.
25//!
26//! # The document GROUPS them, and `resources` is reserved for that
27//!
28//! Struct-flat, document-nested: the spine grows one `resources` field holding a `<Root>Resources`
29//! block, so a deployment writes `[resources.egemma]` and every resource's section is under one
30//! roof. That is what makes `resources` a reserved mount — a member named `resources` would be a
31//! second meaning for the same key — and the derive refuses one by name.
32//!
33//! # A SECTION is emitted for the resources that HAVE one
34//!
35//! [`ResourceSource::Section`] is the only source a document can carry, so it is the only one with a
36//! field in the block. A `factory` resource's options close over something a document cannot hold —
37//! a runtime handle, an open connection — or are computed by a function the declaration names, and
38//! writing a section for one is refused where the reader is looking at the file: the field does not
39//! exist, and `deny_unknown_fields` names it.
40//!
41//! A root that declares no document-sourced resource at all gets no block and no `resources` field,
42//! which keeps the emitted spine of every root that has none byte-for-byte what it was. A document
43//! that writes `resources` at such a root is refused by the same unknown-field rule.
44
45use proc_macro2::TokenStream;
46use quote::{format_ident, quote};
47
48use crate::emit::{framework, leading, vendored};
49
50#[cfg(test)]
51mod tests;
52
53/// `<Root>Resources` — the name a root's own resource block takes.
54///
55/// The options spine's rule, one field over: the type is derived from the USER's root, so a `Media`
56/// configured by a `MediaOptions` groups its resources in a `MediaResources`.
57#[must_use]
58pub fn default_resources_name(root: &syn::Ident) -> syn::Ident {
59 format_ident!("{root}Resources")
60}
61
62/// The mount name the resource block is grouped under, which no member may take.
63pub const RESERVED_MOUNT: &str = "resources";
64
65/// WHERE one declared resource's options come from — the emitter's half of the single-source law.
66///
67/// It mirrors the framework's own vocabulary and adds the one thing an emission needs and a runtime
68/// does not: the PATH a named initializer was written as, which is a token and never a value.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub enum ResourceSource {
71 /// `#[ingraph(resource)]` — the deployment's `[resources.<mount>]` section.
72 Section,
73 /// `#[ingraph(resource(factory))]` — the application's own `prepare` closure.
74 Prepare,
75 /// `#[ingraph(resource(factory = "path::to::fn"))]` — a function the create walk calls itself.
76 Initializer(syn::Path),
77}
78
79impl ResourceSource {
80 /// Whether this resource takes a field in the emitted block.
81 #[must_use]
82 pub const fn is_section(&self) -> bool {
83 matches!(self, Self::Section)
84 }
85
86 /// Whether the emitted create walk builds it, rather than the application's `prepare`.
87 #[must_use]
88 pub const fn is_walked(&self) -> bool {
89 !matches!(self, Self::Prepare)
90 }
91
92 /// The framework word this source declares itself as.
93 fn word(&self, krate: &syn::Path) -> TokenStream {
94 let source = framework(krate, &["resource"], "ResourceSource");
95 match self {
96 Self::Section => quote!(#source::Section),
97 Self::Prepare => quote!(#source::Prepare),
98 Self::Initializer(_) => quote!(#source::Initializer),
99 }
100 }
101}
102
103/// ONE resource field of a graph root, validated and ready to emit.
104///
105/// PLAIN, for the reason every model in this crate has plain fields: the derive today and a manifest
106/// front end later build the same thing and reach the same emitter.
107#[derive(Debug, Clone)]
108pub struct ResourceField {
109 /// The mount — the field's own identifier, which is the document's key and the name a refusal
110 /// reports the resource under.
111 pub mount: syn::Ident,
112 /// The declared type. The field spells the THING, so this is the resource itself and its options
113 /// are reached through the contract.
114 pub ty: syn::Type,
115 /// The ONE source its declaration named.
116 pub source: ResourceSource,
117 /// Whether the field wrote `teardown` — the goodbye opt-in, which COMPOSES with either factory
118 /// form.
119 ///
120 /// It is a second axis rather than a fourth source, and it has to be: where the options come from
121 /// and whether the built value has something to say on the way out are unrelated questions, and
122 /// folding them into one enum would give the grammar a spelling per pair.
123 pub teardown: bool,
124}
125
126/// One root's resource catalog, ready to emit.
127///
128/// It borrows for [`OptionsSpine`](crate::options::OptionsSpine)'s reason: what it needs is the list
129/// the root model already holds, and a second copy is a second thing to keep in step.
130#[derive(Debug, Clone, Copy)]
131pub struct Catalog<'a> {
132 /// Where `ingraph` lives, as the declaration named it.
133 pub krate: &'a syn::Path,
134 /// The root's own visibility — what the block and its accessors take.
135 pub vis: &'a syn::Visibility,
136 /// The root type, whose name the block derives its own from.
137 pub root: &'a syn::Ident,
138 /// The RESOURCES, in declaration order.
139 pub resources: &'a [ResourceField],
140}
141
142impl Catalog<'_> {
143 /// Every resource whose options come from the document, in declaration order.
144 pub fn sections(&self) -> impl Iterator<Item = &ResourceField> {
145 self
146 .resources
147 .iter()
148 .filter(|resource| resource.source.is_section())
149 }
150
151 /// Whether the spine carries a `resources` field at all — see the module note.
152 #[must_use]
153 pub fn has_block(&self) -> bool {
154 self.sections().next().is_some()
155 }
156
157 /// The block a deployment writes its resource sections in, and the walk that declares every
158 /// resource whether or not it has one.
159 #[must_use]
160 pub fn emit(&self) -> TokenStream {
161 let block = self.block();
162 let walk = self.walk();
163 quote! {
164 #block
165 #walk
166 }
167 }
168
169 /// `<Root>Resources` — one field per document-sourced resource, plus its accessors and a `Debug`
170 /// that reports presence.
171 ///
172 /// Nothing at all where no resource takes a section, which is what keeps a root that declares none
173 /// exactly as it was.
174 fn block(&self) -> TokenStream {
175 if !self.has_block() {
176 return TokenStream::new();
177 }
178 let krate = self.krate;
179 let deserialized = self.declaration(true);
180 let plain = self.declaration(false);
181 let methods = self.methods();
182 let debug = self.debug();
183 let if_serde = quote!(#krate::__private::gate::if_serde);
184 let if_no_serde = quote!(#krate::__private::gate::if_no_serde);
185 quote! {
186 #if_serde ! { #deserialized }
187 #if_no_serde ! { #plain }
188 #methods
189 #debug
190 }
191 }
192
193 /// One lane's struct — with serde's derive and words where this build has serde.
194 ///
195 /// Two lanes for [`options`](crate::options)' reason, which is the same one every emitted
196 /// document type has: a derive is an attribute, and an attribute cannot be added by a macro that
197 /// expands to nothing, so the declaration is written once inside each half of the gate.
198 fn declaration(&self, deserialized: bool) -> TokenStream {
199 let vis = self.vis;
200 let root = self.root;
201 let name = default_resources_name(root);
202 let resource = framework(self.krate, &["resource"], "AsyncResource");
203
204 let fields = self.sections().map(|field| {
205 let (mount, ty) = (&field.mount, &field.ty);
206 let doc = leading(&format!(
207 "What this deployment builds `{mount}` with — `None` being the resource at its options' own \
208 `Default`.\n\nThe field NAME is the mount name, so a document's key is the word the \
209 declaration wrote: `[resources.{mount}]`."
210 ));
211 let default = deserialized.then(|| quote!(#[serde(default)]));
212 quote! {
213 #[doc = #doc]
214 #default
215 pub(crate) #mount: ::core::option::Option<<#ty as #resource>::Options>,
216 }
217 });
218
219 let derives = if deserialized {
220 let deserialize = framework(self.krate, &["serde"], "Deserialize");
221 let serde = vendored(self.krate, "serde");
222 quote! {
223 #[derive(::core::default::Default, #deserialize)]
224 #[serde(crate = #serde, deny_unknown_fields)]
225 }
226 } else {
227 quote!(#[derive(::core::default::Default)])
228 };
229
230 let doc = leading(&format!(
231 "What ONE DEPLOYMENT of [`{root}`] builds its shared resources with — one section per \
232 document-sourced resource, absent for the ones it says nothing about.\n\nAn absent section \
233 is the resource at its options' own `Default`, and an options type without one has said its \
234 knobs are mandatory: the create walk then refuses by name, which is the node side's rule one \
235 tier over.\n\nA resource declared `factory` has NO field here. Its options come from the \
236 application's own hand or from the function its declaration names, and a section for one is \
237 refused as an unknown field, where the reader is looking at the file."
238 ));
239 quote! {
240 #[doc = #doc]
241 #derives
242 #vis struct #name {
243 #(#fields)*
244 }
245 }
246 }
247
248 /// The accessor family: one `with_<mount>` and one borrow per document-sourced resource.
249 ///
250 /// The spine's own shape one field over — construction is the default plus one builder per member
251 /// — and ungated for the same reason, the two declarations above being one struct under two
252 /// attribute sets.
253 fn methods(&self) -> TokenStream {
254 let vis = self.vis;
255 let name = default_resources_name(self.root);
256 let resource = framework(self.krate, &["resource"], "AsyncResource");
257
258 let methods = self.sections().map(|field| {
259 let (mount, ty) = (&field.mount, &field.ty);
260 let with = format_ident!("with_{mount}");
261 let held = quote!(<#ty as #resource>::Options);
262 let with_doc = leading(&format!(
263 "Build `{mount}` with `options` — the door a deployment states in code rather than in a \
264 document."
265 ));
266 let borrow_doc = leading(&format!(
267 "What `{mount}` is to be built with, or `None` where this deployment wrote no section for \
268 it."
269 ));
270 quote! {
271 #[doc = #with_doc]
272 #[inline]
273 #[must_use]
274 #vis fn #with(mut self, options: #held) -> Self {
275 self.#mount = ::core::option::Option::Some(options);
276 self
277 }
278
279 #[doc = #borrow_doc]
280 #[inline]
281 #[must_use]
282 #vis fn #mount(&self) -> ::core::option::Option<&#held> {
283 self.#mount.as_ref()
284 }
285 }
286 });
287
288 quote! {
289 impl #name {
290 #(#methods)*
291 }
292 }
293 }
294
295 /// A `Debug` reporting each resource's PRESENCE, and never the options themselves.
296 ///
297 /// The options spine's trade, made again for its reason: a resource's options are the author's
298 /// type, and deriving here would put a `Debug` bound on every one of them for the benefit of this
299 /// line.
300 fn debug(&self) -> TokenStream {
301 let name = default_resources_name(self.root);
302 let fields = self.sections().map(|field| {
303 let key = field.mount.to_string();
304 let mount = &field.mount;
305 quote!(.field(#key, &::core::option::Option::is_some(&self.#mount)))
306 });
307 quote! {
308 impl ::core::fmt::Debug for #name {
309 fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
310 f.debug_struct(::core::stringify!(#name))
311 #(#fields)*
312 .finish()
313 }
314 }
315 }
316 }
317
318 /// `<Root>::resource_iter` and `<Root>::resources` — the RESOURCE half of the walk, and the
319 /// catalog it collects into.
320 ///
321 /// Inherent for [`type_iter`](crate::graph::GraphModel)'s reason, and it is the same mechanism: an
322 /// impl may not add a where clause to a trait method, and this walk states one citizenship
323 /// predicate per resource field. That predicate is the teaching the ruling asks for — a field
324 /// marked `resource` whose type never took `#[ingraph::resource]`, or never implemented
325 /// [`AsyncResource`], is `E0277` where the ROOT is written.
326 ///
327 /// `resources` drives it into the framework's own collector, which is infallible — so the emitted
328 /// body names the impossible arm rather than unwrapping it.
329 fn walk(&self) -> TokenStream {
330 let krate = self.krate;
331 let vis = self.vis;
332 let root = self.root;
333 let resources = framework(krate, &["resource"], "ResourceCatalog");
334 let visitor = framework(krate, &["resource"], "ResourceVisitor");
335
336 let declared = self.resources.iter().map(|field| {
337 let ty = &field.ty;
338 let mount = field.mount.to_string();
339 let source = field.source.word(krate);
340 quote! {
341 #visitor::next_resource::<#ty>(visitor, #mount, #source)?;
342 }
343 });
344
345 let iter_doc = leading(
346 "Apply `visitor` to every RESOURCE this graph declares, in the order its fields are \
347 written.\n\nEach call carries the three facts a resource declaration states: the type, the \
348 mount it is written under, and the ONE source its options come from.\n\n# Errors\n\nThe first \
349 resource the visitor refuses, with the ones after it unvisited.",
350 );
351 let catalog_doc = leading(&format!(
352 "THE ROOT CATALOG of [`{root}`] — every declared resource, its mount, and its one options \
353 source.\n\nWhat `launch` installs on the plan it is handed, so a deployment never writes the \
354 declared set: the root's fields ARE it."
355 ));
356
357 quote! {
358 impl #root {
359 #[doc = #iter_doc]
360 #vis fn resource_iter<__IgResources>(
361 visitor: &mut __IgResources,
362 ) -> ::core::result::Result<(), <__IgResources as #visitor>::Error>
363 where
364 __IgResources: #visitor,
365 {
366 #(#declared)*
367 ::core::result::Result::Ok(())
368 }
369
370 #[doc = #catalog_doc]
371 #[must_use]
372 #vis fn resources() -> #resources {
373 let mut declared = #resources::new();
374 match Self::resource_iter(&mut declared) {
375 ::core::result::Result::Ok(()) => declared,
376 ::core::result::Result::Err(never) => match never {},
377 }
378 }
379 }
380 }
381 }
382}