Skip to main content

gurafi/
schema.rs

1//! The schema builder.
2//!
3//! A [`Schema`] owns the definitions being assembled. Types are created through closures that
4//! receive a builder, which keeps the definition of a type next to the type itself:
5//!
6//! ```
7//! use gurafi::{Object, Schema, NoArgs};
8//!
9//! #[derive(Object)]
10//! struct Giraffe {
11//!     name: String,
12//! }
13//!
14//! struct Ctx;
15//!
16//! let mut schema = Schema::<Ctx>::new();
17//! schema.object::<Giraffe>(|o| {
18//!     o.expose(gurafi::expose!(Giraffe::name));
19//! });
20//! schema.query(|q| {
21//!     q.field("giraffe", |_: NoArgs, _: &Ctx| Giraffe { name: "Melman".into() });
22//! });
23//! let schema = schema.build().expect("valid schema");
24//! assert!(schema.object_type("Giraffe").is_some());
25//! ```
26//!
27//! A type's definition can be spread over several [`Schema::object_fields`],
28//! [`Schema::interface_fields`], [`Schema::query_fields`], [`Schema::mutation_fields`] and
29//! [`Schema::subscription_fields`] calls, including from different modules. Declarations merge;
30//! duplicate field names are still build errors.
31
32use std::{
33    any::TypeId,
34    collections::{HashMap, HashSet},
35    marker::PhantomData,
36    sync::Arc,
37};
38
39use futures::{Stream, StreamExt};
40use gql::{AppliedDirective, DirectiveDefinition, GraphQLError, Name, TypeRef};
41use indexmap::IndexMap;
42
43use crate::{
44    error::SchemaError,
45    error_union::{ErrorUnionModel, ResultSuccess, result_union_type_ref},
46    expose::Expose,
47    field::{
48        AuthGuard, FieldCheck, FieldConfig, InterfaceFieldConfig, RawFieldArgs, ValidationSlot,
49        apply_auth_guard, read_raw_field,
50    },
51    plugin::{Plugin, PluginTargets, apply_plugins},
52    registry::TypeRegistry,
53    traits::{
54        EnumModel, InputObject, IntoValue, ObjectModel, OutputType, ScalarValue, coerce_args,
55        coerce_args_without_validation, model_ref,
56    },
57};
58
59/// A boxed future returned by an asynchronous resolver.
60///
61/// Asynchronous resolvers accept a closure returning this type, so a resolver is written as
62/// `Box::pin(async move { ... })`. The box is allocated once per field resolution; `gql`
63/// already boxes every resolver future, so this is the same allocation the executor needs
64/// anyway. Fields declared with [`ObjectBuilder::expose`] do not use this type: they install a
65/// synchronous property resolver and allocate no future.
66pub type BoxFuture<'a, T> = futures::future::BoxFuture<'a, T>;
67
68/// A reference to an object type whose GraphQL name may be computed at runtime.
69///
70/// An object reference ties a Rust model to a GraphQL type name. The model still drives
71/// `is_type_of` and the resolvers a builder receives; the name is just data. Refs are created by
72/// [`Schema::object_ref`] (or [`Schema::object`] for the derived name) and consumed by
73/// [`Schema::implement`].
74///
75/// The model parameter means a reference cannot be accidentally used with a different model's
76/// resolvers. Two references compare equal when they name the same GraphQL type.
77pub struct ObjectRef<M: ObjectModel> {
78    name: Name,
79    marker: PhantomData<fn() -> M>,
80}
81
82impl<M: ObjectModel> ObjectRef<M> {
83    fn new(name: Name) -> Self {
84        Self {
85            name,
86            marker: PhantomData,
87        }
88    }
89
90    /// The object's GraphQL name.
91    #[must_use]
92    pub fn name(&self) -> &str {
93        &self.name
94    }
95
96    /// A reference to this object with no list or nullability wrappers.
97    #[must_use]
98    pub fn type_ref(&self) -> TypeRef {
99        TypeRef::named(Arc::clone(&self.name))
100    }
101
102    /// Whether this object is a possible type of `abstract_type` in `schema`.
103    #[must_use]
104    pub fn is_possible_type(&self, schema: &gql::Schema, abstract_type: &str) -> bool {
105        schema.is_possible_type(abstract_type, self.name())
106    }
107
108    /// The model's compile-time GraphQL name.
109    ///
110    /// The object may be registered under a different runtime name; this is the name
111    /// `#[derive(Object)]` generated.
112    #[must_use]
113    pub fn model_name(&self) -> &'static str {
114        M::NAME
115    }
116}
117
118impl<M: ObjectModel> Clone for ObjectRef<M> {
119    fn clone(&self) -> Self {
120        Self::new(Arc::clone(&self.name))
121    }
122}
123
124impl<M: ObjectModel> std::fmt::Debug for ObjectRef<M> {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        f.debug_tuple("ObjectRef").field(&self.name).finish()
127    }
128}
129
130impl<M: ObjectModel> PartialEq for ObjectRef<M> {
131    fn eq(&self, other: &Self) -> bool {
132        self.name == other.name
133    }
134}
135
136impl<M: ObjectModel> Eq for ObjectRef<M> {}
137
138impl<M: ObjectModel> std::hash::Hash for ObjectRef<M> {
139    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
140        self.name.hash(state);
141    }
142}
143
144impl<M: ObjectModel> From<&ObjectRef<M>> for TypeRef {
145    fn from(reference: &ObjectRef<M>) -> Self {
146        reference.type_ref()
147    }
148}
149
150/// An interface definition created by [`Schema::interface_ref`].
151#[derive(Clone, Debug, PartialEq, Eq, Hash)]
152pub struct InterfaceRef {
153    name: Name,
154}
155
156impl InterfaceRef {
157    fn new(name: Name) -> Self {
158        Self { name }
159    }
160
161    /// The interface's GraphQL name.
162    #[must_use]
163    pub fn name(&self) -> &str {
164        &self.name
165    }
166
167    /// A reference to this interface with no list or nullability wrappers.
168    #[must_use]
169    pub fn type_ref(&self) -> TypeRef {
170        TypeRef::named(Arc::clone(&self.name))
171    }
172
173    /// Whether `object_type` is a possible type of this interface in `schema`.
174    #[must_use]
175    pub fn is_possible_type(&self, schema: &gql::Schema, object_type: &str) -> bool {
176        schema.is_possible_type(self.name(), object_type)
177    }
178
179    /// Every object type that can appear where this interface is expected.
180    #[must_use]
181    pub fn possible_types(&self, schema: &gql::Schema) -> Vec<Name> {
182        schema.possible_types(self.name())
183    }
184}
185
186impl From<&InterfaceRef> for InterfaceRef {
187    fn from(reference: &InterfaceRef) -> Self {
188        reference.clone()
189    }
190}
191
192/// A union definition created by [`Schema::union_ref`].
193#[derive(Clone, Debug, PartialEq, Eq, Hash)]
194pub struct UnionRef {
195    name: Name,
196}
197
198impl UnionRef {
199    fn new(name: Name) -> Self {
200        Self { name }
201    }
202
203    /// The union's GraphQL name.
204    #[must_use]
205    pub fn name(&self) -> &str {
206        &self.name
207    }
208
209    /// A reference to this union with no list or nullability wrappers.
210    #[must_use]
211    pub fn type_ref(&self) -> TypeRef {
212        TypeRef::named(Arc::clone(&self.name))
213    }
214
215    /// Whether `object_type` is a possible type of this union in `schema`.
216    #[must_use]
217    pub fn is_possible_type(&self, schema: &gql::Schema, object_type: &str) -> bool {
218        schema.is_possible_type(self.name(), object_type)
219    }
220
221    /// Every object type that can appear where this union is expected.
222    #[must_use]
223    pub fn possible_types(&self, schema: &gql::Schema) -> Vec<Name> {
224        schema.possible_types(self.name())
225    }
226}
227
228impl From<&UnionRef> for UnionRef {
229    fn from(reference: &UnionRef) -> Self {
230        reference.clone()
231    }
232}
233
234/// Options applied when a schema is built.
235///
236/// The defaults match [`Schema::build`]: no root descriptions and no reordering.
237#[derive(Clone, Debug, Default)]
238pub struct BuildOptions {
239    query_description: Option<Arc<str>>,
240    mutation_description: Option<Arc<str>>,
241    subscription_description: Option<Arc<str>>,
242    sort_types: bool,
243}
244
245impl BuildOptions {
246    /// Default options.
247    #[must_use]
248    pub fn new() -> Self {
249        Self::default()
250    }
251
252    /// Set the query root type's description.
253    #[must_use]
254    pub fn query_description(mut self, description: impl Into<Arc<str>>) -> Self {
255        self.query_description = Some(description.into());
256        self
257    }
258
259    /// Set the mutation root type's description.
260    #[must_use]
261    pub fn mutation_description(mut self, description: impl Into<Arc<str>>) -> Self {
262        self.mutation_description = Some(description.into());
263        self
264    }
265
266    /// Set the subscription root type's description.
267    #[must_use]
268    pub fn subscription_description(mut self, description: impl Into<Arc<str>>) -> Self {
269        self.subscription_description = Some(description.into());
270        self
271    }
272
273    /// Sort named types by name when handing them to `gql`.
274    ///
275    /// Without this, types are registered in declaration order. Sorting makes SDL output and
276    /// introspection snapshots stable across modules and registration order.
277    #[must_use]
278    pub fn sort_types(mut self, sort: bool) -> Self {
279        self.sort_types = sort;
280        self
281    }
282}
283
284/// A field that inherits its type and arguments from an implemented interface's field.
285#[derive(Clone, Debug)]
286pub(crate) struct PendingInherited {
287    object: Name,
288    field: Name,
289    expected_args: Vec<(Name, TypeRef)>,
290}
291
292/// A type-safe, code-first GraphQL schema builder.
293///
294/// `Ctx` is the per-request context type (an authenticated user, database handles, request
295/// identifiers). It is supplied by the server through
296/// [`gql::ExecutionOptions::with_context`] and passed to every resolver and authorization
297/// predicate.
298///
299/// Build a schema by registering objects, interfaces and unions, then adding root fields:
300///
301/// ```
302/// use gurafi::{Object, Schema, NoArgs};
303///
304/// #[derive(Object)]
305/// struct Greeting {
306///     message: String,
307/// }
308///
309/// struct Ctx {}
310///
311/// let mut schema = Schema::<Ctx>::new();
312/// schema.object::<Greeting>(|o| {
313///     o.expose(gurafi::expose!(Greeting::message));
314/// });
315/// schema.query(|q| {
316///     q.field("greeting", |_: NoArgs, _: &Ctx| Greeting {
317///         message: "Hello".into(),
318///     });
319/// });
320/// let schema = schema.build().expect("valid schema");
321/// ```
322pub struct Schema<Ctx: 'static = ()> {
323    registry: TypeRegistry,
324    objects: IndexMap<Name, gql::ObjectType>,
325    /// The Rust model that owns each object name, so two models cannot silently merge.
326    object_owners: IndexMap<Name, TypeId>,
327    /// Names for which an ownership collision has already been reported.
328    object_conflicts: HashSet<Name>,
329    /// Fields declared with `raw_field`/`raw_field_with`, per object. A raw object must not also
330    /// carry resolver-backed fields, because those would receive the raw map instead of the
331    /// model.
332    raw_fields: IndexMap<Name, HashSet<Name>>,
333    interfaces: IndexMap<Name, gql::InterfaceType>,
334    unions: IndexMap<Name, gql::UnionType>,
335    query: Vec<gql::Field>,
336    mutation: Vec<gql::Field>,
337    subscription: Vec<gql::Field>,
338    errors: Vec<GraphQLError>,
339    query_name: String,
340    mutation_name: String,
341    subscription_name: String,
342    description: Option<Arc<str>>,
343    checks: Vec<FieldCheck>,
344    object_auth: IndexMap<String, Vec<Arc<AuthGuard<Ctx>>>>,
345    /// The latest `auth_error` declared for an object, even when that declaration added no
346    /// predicate. It is applied to the existing rule instead of replacing it.
347    object_auth_error: IndexMap<String, Arc<str>>,
348    interface_auth: IndexMap<String, Vec<Arc<AuthGuard<Ctx>>>>,
349    interface_auth_error: IndexMap<String, Arc<str>>,
350    interface_field_auth: IndexMap<String, IndexMap<Name, Arc<AuthGuard<Ctx>>>>,
351    pending_inherited: Vec<PendingInherited>,
352    /// Custom directive definitions registered with [`Schema::directive`].
353    directive_definitions: Vec<DirectiveDefinition>,
354    /// Directive applications for named types, kept by name so a type registered later still
355    /// receives them.
356    type_directives: IndexMap<Name, Vec<AppliedDirective>>,
357    /// Directive applications for field arguments, keyed by type, field and argument name.
358    argument_directives: Vec<(Name, Name, Name, AppliedDirective)>,
359    /// Directive applications for input object fields, keyed by type and field name.
360    input_field_directives: Vec<(Name, Name, AppliedDirective)>,
361    /// Build-time extensions, applied to every field once when the schema is built.
362    plugins: Vec<Arc<dyn Plugin<Ctx>>>,
363    marker: PhantomData<fn() -> Ctx>,
364}
365
366impl<Ctx: 'static> Clone for Schema<Ctx> {
367    fn clone(&self) -> Self {
368        Self {
369            registry: self.registry.clone(),
370            objects: self.objects.clone(),
371            object_owners: self.object_owners.clone(),
372            object_conflicts: self.object_conflicts.clone(),
373            raw_fields: self.raw_fields.clone(),
374            interfaces: self.interfaces.clone(),
375            unions: self.unions.clone(),
376            query: self.query.clone(),
377            mutation: self.mutation.clone(),
378            subscription: self.subscription.clone(),
379            errors: self.errors.clone(),
380            query_name: self.query_name.clone(),
381            mutation_name: self.mutation_name.clone(),
382            subscription_name: self.subscription_name.clone(),
383            description: self.description.clone(),
384            checks: self.checks.clone(),
385            object_auth: self.object_auth.clone(),
386            object_auth_error: self.object_auth_error.clone(),
387            interface_auth: self.interface_auth.clone(),
388            interface_auth_error: self.interface_auth_error.clone(),
389            interface_field_auth: self.interface_field_auth.clone(),
390            pending_inherited: self.pending_inherited.clone(),
391            directive_definitions: self.directive_definitions.clone(),
392            type_directives: self.type_directives.clone(),
393            argument_directives: self.argument_directives.clone(),
394            input_field_directives: self.input_field_directives.clone(),
395            plugins: self.plugins.clone(),
396            marker: PhantomData,
397        }
398    }
399}
400
401impl<Ctx: 'static> Default for Schema<Ctx> {
402    fn default() -> Self {
403        Self::new()
404    }
405}
406
407impl<Ctx: 'static> std::fmt::Debug for Schema<Ctx> {
408    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
409        f.debug_struct("Schema")
410            .field("objects", &self.objects.len())
411            .field("interfaces", &self.interfaces.len())
412            .field("unions", &self.unions.len())
413            .field("query_fields", &self.query.len())
414            .field("mutation_fields", &self.mutation.len())
415            .field("subscription_fields", &self.subscription.len())
416            .field("plugins", &self.plugins.len())
417            .finish_non_exhaustive()
418    }
419}
420
421impl<Ctx: 'static> Schema<Ctx> {
422    /// Create an empty schema.
423    ///
424    /// Root type names default to `Query`, `Mutation` and `Subscription`. A root type is only
425    /// added to the schema when it has at least one field.
426    #[must_use]
427    pub fn new() -> Self {
428        Self {
429            registry: TypeRegistry::new(),
430            objects: IndexMap::new(),
431            object_owners: IndexMap::new(),
432            object_conflicts: HashSet::new(),
433            raw_fields: IndexMap::new(),
434            interfaces: IndexMap::new(),
435            unions: IndexMap::new(),
436            query: Vec::new(),
437            mutation: Vec::new(),
438            subscription: Vec::new(),
439            errors: Vec::new(),
440            query_name: "Query".to_owned(),
441            mutation_name: "Mutation".to_owned(),
442            subscription_name: "Subscription".to_owned(),
443            description: None,
444            checks: Vec::new(),
445            object_auth: IndexMap::new(),
446            object_auth_error: IndexMap::new(),
447            interface_auth: IndexMap::new(),
448            interface_auth_error: IndexMap::new(),
449            interface_field_auth: IndexMap::new(),
450            pending_inherited: Vec::new(),
451            directive_definitions: Vec::new(),
452            type_directives: IndexMap::new(),
453            argument_directives: Vec::new(),
454            input_field_directives: Vec::new(),
455            plugins: Vec::new(),
456            marker: PhantomData,
457        }
458    }
459
460    /// Set the schema's description.
461    pub fn description(&mut self, description: impl Into<Arc<str>>) -> &mut Self {
462        self.description = Some(description.into());
463        self
464    }
465
466    /// Register a build-time plugin.
467    ///
468    /// Plugins are stored and applied once when the schema is built (through [`Schema::build`],
469    /// [`Schema::build_with`] or [`Schema::build_clone`]), after every type and field has been
470    /// declared. Registering a plugin before or after declaring fields is therefore equivalent,
471    /// and fields added later are always covered.
472    ///
473    /// See the [`crate::plugin`] module documentation for ordering and coverage, and
474    /// [`crate::TracingPlugin`], [`crate::ResponseExtensionPlugin`] and
475    /// [`crate::MockPlugin`] for the built-ins.
476    ///
477    /// ```
478    /// use gurafi::{FieldMeta, NoArgs, Object, Plugin, Schema};
479    ///
480    /// struct AddDescription;
481    ///
482    /// impl Plugin<Ctx> for AddDescription {
483    ///     fn field(&self, meta: &FieldMeta<'_>, field: &mut gql::Field) {
484    ///         if meta.is_root {
485    ///             field.description = Some("A root field".into());
486    ///         }
487    ///     }
488    /// }
489    ///
490    /// # struct Ctx;
491    /// # #[derive(Object)] struct Giraffe { name: String }
492    /// let mut schema = Schema::<Ctx>::new();
493    /// schema.plugin(AddDescription);
494    /// schema.query(|q| {
495    ///     q.field("ok", |_: NoArgs, _: &Ctx| true);
496    /// });
497    /// # let _ = schema.build().expect("valid schema");
498    /// ```
499    pub fn plugin<P: Plugin<Ctx>>(&mut self, plugin: P) -> &mut Self {
500        self.plugins.push(Arc::new(plugin));
501        self
502    }
503
504    /// Register a custom directive definition.
505    ///
506    /// The definition supplies the name, description, permitted locations, arguments and whether
507    /// the directive is repeatable. Every application is checked against it when the schema is
508    /// built: an unknown directive, a location the definition does not allow, an argument of the
509    /// wrong type and a duplicate application of a non-repeatable directive are all build errors.
510    ///
511    /// Definitions are printed by [`gql::Schema::sdl`] and exposed through introspection's
512    /// `__schema.directives`, so a client can discover them. The built-in directives (`@skip`,
513    /// `@include`, `@deprecated`, `@specifiedBy` and `@oneOf`) are already registered; defining
514    /// one again is a build error.
515    ///
516    /// Apply the directive with [`Schema::type_directive`] for a named type, or with the
517    /// declaration-site methods ([`ObjectBuilder::directive`], [`InterfaceBuilder::directive`],
518    /// [`UnionBuilder::directive`] and [`FieldConfig::directive`]).
519    ///
520    /// ```
521    /// use gurafi::{NoArgs, Object, Schema};
522    ///
523    /// struct Ctx;
524    ///
525    /// #[derive(Object)]
526    /// struct Giraffe {
527    ///     name: String,
528    /// }
529    ///
530    /// let mut schema = Schema::<Ctx>::new();
531    /// schema.directive(
532    ///     gql::DirectiveDefinition::new("tag")
533    ///         .description("A documentation tag.")
534    ///         .location(gql::ast::DirectiveLocation::Object)
535    ///         .location(gql::ast::DirectiveLocation::FieldDefinition)
536    ///         .arg(gql::InputValue::new("name", gql::TypeRef::string())),
537    /// );
538    /// schema.type_directive(
539    ///     "Giraffe",
540    ///     gql::AppliedDirective::new("tag").argument("name", "animal"),
541    /// );
542    /// schema.object::<Giraffe>(|o| {
543    ///     o.expose(gurafi::expose!(Giraffe::name));
544    /// });
545    /// schema.query(|q| {
546    ///     q.field("giraffe", |_: NoArgs, _: &Ctx| Giraffe { name: "Melman".into() })
547    ///         .directive(gql::AppliedDirective::new("tag").argument("name", "entry"));
548    /// });
549    /// # let _ = schema.build().expect("valid schema");
550    /// ```
551    pub fn directive(&mut self, definition: DirectiveDefinition) -> &mut Self {
552        self.directive_definitions.push(definition);
553        self
554    }
555
556    /// Apply `directive` to the type named `name`, whatever its kind.
557    ///
558    /// The name may refer to an object, interface, union, scalar, enum, input object or a root
559    /// operation type. The type does not have to exist yet: applications are recorded by name and
560    /// attached when the schema is built, so this works for a type registered in another module
561    /// or after this call. A name that is never registered is a build error.
562    ///
563    /// Calling this more than once adds each application, which is how a repeatable directive is
564    /// used. A non-repeatable directive applied twice to the same type is reported by schema
565    /// validation.
566    ///
567    /// ```
568    /// use gurafi::{NoArgs, Object, Schema};
569    ///
570    /// struct Ctx;
571    ///
572    /// #[derive(Object)]
573    /// struct Giraffe {
574    ///     name: String,
575    /// }
576    ///
577    /// let mut schema = Schema::<Ctx>::new();
578    /// schema.directive(
579    ///     gql::DirectiveDefinition::new("tag")
580    ///         .location(gql::ast::DirectiveLocation::Object)
581    ///         .arg(gql::InputValue::new("name", gql::TypeRef::string())),
582    /// );
583    /// schema.type_directive(
584    ///     "Giraffe",
585    ///     gql::AppliedDirective::new("tag").argument("name", "animal"),
586    /// );
587    /// # schema.object::<Giraffe>(|o| {
588    /// #     o.expose(gurafi::expose!(Giraffe::name));
589    /// # });
590    /// # schema.query(|q| {
591    /// #     q.field("giraffe", |_: NoArgs, _: &Ctx| Giraffe { name: "Melman".into() });
592    /// # });
593    /// # schema.build().expect("valid schema");
594    /// ```
595    pub fn type_directive(
596        &mut self,
597        name: impl Into<Name>,
598        directive: AppliedDirective,
599    ) -> &mut Self {
600        self.type_directives
601            .entry(name.into())
602            .or_default()
603            .push(directive);
604        self
605    }
606
607    /// Apply `directive` to one argument of one field.
608    ///
609    /// `type_name` may name an object or interface, or a root operation type (`Query` by
610    /// default). `field_name` is the field's GraphQL name and `argument_name` is one of its
611    /// arguments. The field and argument do not have to exist yet; they are resolved when the
612    /// schema is built, and a missing type, field or argument is a build error.
613    ///
614    /// This covers field arguments, including root fields. Directive-definition arguments are
615    /// not covered: set them directly on [`gql::InputValue`] before passing the definition to
616    /// [`Schema::directive`]. Use [`Schema::input_field_directive`] for input object fields.
617    ///
618    /// ```
619    /// use gurafi::{Input, NoArgs, Object, Schema};
620    ///
621    /// struct Ctx;
622    ///
623    /// #[derive(Object)]
624    /// struct Giraffe {
625    ///     name: String,
626    /// }
627    ///
628    /// #[derive(Input)]
629    /// struct NameArgs {
630    ///     name: String,
631    /// }
632    ///
633    /// let mut schema = Schema::<Ctx>::new();
634    /// schema.directive(
635    ///     gql::DirectiveDefinition::new("tag")
636    ///         .location(gql::ast::DirectiveLocation::ArgumentDefinition)
637    ///         .arg(gql::InputValue::new("name", gql::TypeRef::string())),
638    /// );
639    /// schema.object::<Giraffe>(|o| {
640    ///     o.field("name", |g: &Giraffe, _: NameArgs, _: &Ctx| g.name.clone());
641    /// });
642    /// schema.argument_directive(
643    ///     "Giraffe",
644    ///     "name",
645    ///     "name",
646    ///     gql::AppliedDirective::new("tag").argument("name", "public"),
647    /// );
648    /// # schema.query(|q| {
649    /// #     q.field("giraffe", |_: NoArgs, _: &Ctx| Giraffe { name: "Melman".into() });
650    /// # });
651    /// # schema.build().expect("valid schema");
652    /// ```
653    pub fn argument_directive(
654        &mut self,
655        type_name: impl Into<Name>,
656        field_name: impl Into<Name>,
657        argument_name: impl Into<Name>,
658        directive: AppliedDirective,
659    ) -> &mut Self {
660        self.argument_directives.push((
661            type_name.into(),
662            field_name.into(),
663            argument_name.into(),
664            directive,
665        ));
666        self
667    }
668
669    /// Apply `directive` to one field of an input object.
670    ///
671    /// The input object and field do not have to exist yet; both are resolved when the schema is
672    /// built, and a missing type or field is a build error. Input objects are registered by using
673    /// them as an argument type or through `#[derive(Input)]`'s name, so this is the way to tag
674    /// an input field without redefining the Rust type.
675    ///
676    /// ```
677    /// use gurafi::{Input, NoArgs, Object, Schema};
678    ///
679    /// struct Ctx;
680    ///
681    /// #[derive(Object)]
682    /// struct Giraffe {
683    ///     name: String,
684    /// }
685    ///
686    /// #[derive(Input)]
687    /// #[graphql(name = "FilterInput")]
688    /// struct Filter {
689    ///     name: Option<String>,
690    /// }
691    ///
692    /// let mut schema = Schema::<Ctx>::new();
693    /// schema.directive(
694    ///     gql::DirectiveDefinition::new("tag")
695    ///         .location(gql::ast::DirectiveLocation::InputFieldDefinition)
696    ///         .arg(gql::InputValue::new("name", gql::TypeRef::string())),
697    /// );
698    /// schema.object::<Giraffe>(|o| {
699    ///     o.field("name", |g: &Giraffe, _: Filter, _: &Ctx| g.name.clone());
700    /// });
701    /// schema.input_field_directive(
702    ///     "FilterInput",
703    ///     "name",
704    ///     gql::AppliedDirective::new("tag").argument("name", "public"),
705    /// );
706    /// # schema.query(|q| {
707    /// #     q.field("giraffe", |_: NoArgs, _: &Ctx| Giraffe { name: "Melman".into() });
708    /// # });
709    /// # schema.build().expect("valid schema");
710    /// ```
711    pub fn input_field_directive(
712        &mut self,
713        type_name: impl Into<Name>,
714        field_name: impl Into<Name>,
715        directive: AppliedDirective,
716    ) -> &mut Self {
717        self.input_field_directives
718            .push((type_name.into(), field_name.into(), directive));
719        self
720    }
721
722    /// Override the query root type's name. Defaults to `Query`.
723    pub fn query_name(&mut self, name: impl Into<String>) -> &mut Self {
724        self.query_name = name.into();
725        self
726    }
727
728    /// Override the mutation root type's name. Defaults to `Mutation`.
729    pub fn mutation_name(&mut self, name: impl Into<String>) -> &mut Self {
730        self.mutation_name = name.into();
731        self
732    }
733
734    /// Override the subscription root type's name. Defaults to `Subscription`.
735    pub fn subscription_name(&mut self, name: impl Into<String>) -> &mut Self {
736        self.subscription_name = name.into();
737        self
738    }
739
740    /// Register an object type under its derived name.
741    ///
742    /// The GraphQL name and description come from `M`'s [`ObjectModel`] implementation, which
743    /// `#[derive(Object)]` generates. Fields are declared in the closure; a field may return
744    /// any type that implements [`OutputType`], including a type registered later, because
745    /// `gql` resolves type names when the schema is built.
746    ///
747    /// Calling this again for the same model reopens the object and adds fields to it. This is
748    /// how a type's definition can live in several modules. A field name declared twice is
749    /// still a build error.
750    ///
751    /// The returned [`ObjectRef`] can be used as an output type with
752    /// [`ObjectBuilder::field_ref`] and passed back to [`Schema::implement`].
753    pub fn object<M: ObjectModel>(
754        &mut self,
755        build: impl FnOnce(&mut ObjectBuilder<'_, Ctx, M>),
756    ) -> ObjectRef<M> {
757        let reference = self.object_ref(M::NAME);
758        self.implement(&reference, build);
759        reference
760    }
761
762    /// Create (or reopen) an object type whose GraphQL name is computed at runtime.
763    ///
764    /// The model still supplies `is_type_of`, descriptions and the type a resolver receives, but
765    /// the GraphQL name is `name`. Use it for names that only exist after some application
766    /// decision, such as Relay's `UserPostsConnection` or `CreateUserPayload`:
767    ///
768    /// ```
769    /// # use gurafi::{NoArgs, Object, Schema};
770    /// # struct Ctx;
771    /// # #[derive(Object)] struct User { name: String }
772    /// let mut schema = Schema::<Ctx>::new();
773    /// let admin = schema.object_ref::<User>("AdminUser");
774    /// schema.implement(&admin, |o| {
775    ///     o.expose(gurafi::expose!(User::name));
776    /// });
777    /// schema.query(|q| {
778    ///     q.field_ref(&admin, "admin", |_: NoArgs, _: &Ctx| User {
779    ///         name: "ada".into(),
780    ///     });
781    /// });
782    /// # schema.build().expect("valid schema");
783    /// ```
784    ///
785    /// The name is owned by the schema. Calling this twice with the same name and model merges
786    /// the definitions. A different model claiming the same name is a build error.
787    pub fn object_ref<M: ObjectModel>(&mut self, name: impl Into<Name>) -> ObjectRef<M> {
788        let name = name.into();
789        self.validate_type_name("Object", &name);
790        if self.claim_object_name::<M>(&name) {
791            self.ensure_object::<M>(&name);
792        }
793        ObjectRef::new(name)
794    }
795
796    /// Add fields to an object created by [`Schema::object_ref`] (or reopen a derived object).
797    ///
798    /// The reference carries both the runtime name and the model, so this is the typed
799    /// counterpart of [`Schema::object`]. Reopening merges fields and declarations; it never
800    /// replaces an existing definition.
801    pub fn implement<M: ObjectModel>(
802        &mut self,
803        reference: &ObjectRef<M>,
804        build: impl FnOnce(&mut ObjectBuilder<'_, Ctx, M>),
805    ) -> &mut Self {
806        let name = Arc::clone(&reference.name);
807        if !self.claim_object_name::<M>(&name) {
808            return self;
809        }
810        self.ensure_object::<M>(&name);
811        let existing = self.objects.shift_remove(&name);
812        let existing_auth_error = self.object_auth_error.get(&*name).cloned();
813        let raw_fields = self.raw_fields.entry(Arc::clone(&name)).or_default();
814        let mut builder = ObjectBuilder::<Ctx, M>::new(
815            existing,
816            existing_auth_error,
817            &mut self.registry,
818            &mut self.checks,
819            &mut self.pending_inherited,
820            raw_fields,
821            name.clone(),
822        );
823        build(&mut builder);
824        let (object, auth, auth_error) = builder.finish();
825        if let Some(message) = auth_error {
826            self.object_auth_error
827                .insert(name.to_string(), Arc::clone(&message));
828        }
829        if auth.is_empty() {
830            // An `auth_error` without a predicate refines the rule already installed by an
831            // earlier declaration; it must not make the object less guarded.
832            if let Some(message) = self.object_auth_error.get(&*name).cloned() {
833                if let Some(previous) = self
834                    .object_auth
835                    .get_mut(&*name)
836                    .and_then(|guards| guards.last_mut())
837                {
838                    *previous = previous.with_message(Some(message));
839                }
840            }
841        } else {
842            self.object_auth
843                .entry(name.to_string())
844                .or_default()
845                .extend(auth);
846        }
847        self.objects.insert(name, object);
848        self
849    }
850
851    /// Claim an object name for `M`, reporting a collision once.
852    fn claim_object_name<M: ObjectModel>(&mut self, name: &Name) -> bool {
853        match self.object_owners.get(name) {
854            Some(owner) if *owner != TypeId::of::<M>() => {
855                if self.object_conflicts.insert(Arc::clone(name)) {
856                    self.errors.push(GraphQLError::new(format!(
857                        "Object type `{name}` is registered by more than one Rust type. Give one \
858                         of them a distinct GraphQL name, or register this model under its own \
859                         dynamic name."
860                    )));
861                }
862                false
863            }
864            Some(_) => true,
865            None => {
866                self.object_owners
867                    .insert(Arc::clone(name), TypeId::of::<M>());
868                true
869            }
870        }
871    }
872
873    /// Create an empty object definition if the name is not present yet.
874    fn ensure_object<M: ObjectModel>(&mut self, name: &Name) {
875        if self.objects.contains_key(name) {
876            return;
877        }
878        let mut object = gql::ObjectType::new(Arc::clone(name));
879        if let Some(description) = M::description() {
880            object = object.description(description);
881        }
882        object = object.is_type_of(|value| value.as_external::<M>().is_some());
883        self.objects.insert(Arc::clone(name), object);
884    }
885
886    /// Reopen an object type and add more fields to it.
887    ///
888    /// This is an alias for [`Schema::object`] with a name that says the type may already
889    /// exist. Use it when fields are split across modules.
890    pub fn object_fields<M: ObjectModel>(
891        &mut self,
892        build: impl FnOnce(&mut ObjectBuilder<'_, Ctx, M>),
893    ) -> ObjectRef<M> {
894        self.object::<M>(build)
895    }
896
897    /// Add one field to an object without opening a builder closure.
898    ///
899    /// The object is created if it does not exist yet. The returned [`FieldConfig`] can carry
900    /// the usual descriptions, deprecation and authorization options.
901    pub fn object_field<M, T, A, F>(
902        &mut self,
903        name: &'static str,
904        resolver: F,
905    ) -> FieldConfig<'_, Ctx>
906    where
907        M: ObjectModel,
908        T: OutputType + IntoValue + Send + 'static,
909        A: InputObject,
910        F: Fn(&M, A, &Ctx) -> T + Send + Sync + 'static,
911    {
912        let object_name: Name = Arc::from(M::NAME);
913        if self.claim_object_name::<M>(&object_name) {
914            self.ensure_object::<M>(&object_name);
915        }
916        if !self.objects.contains_key(&object_name) {
917            self.objects
918                .insert(Arc::clone(&object_name), new_object::<M>());
919        }
920        let (field, validation) =
921            object_field::<M, Ctx, T, A, F>(name, resolver, &mut self.registry);
922        let field_name = field.name.clone();
923        let object = self
924            .objects
925            .get_mut(&object_name)
926            .expect("the object was just inserted");
927        object.insert_field(field);
928        FieldConfig::for_object_checked(
929            &mut self.registry,
930            &mut object.fields,
931            &mut self.checks,
932            Arc::clone(&object_name),
933            field_name,
934            T::is_optional(),
935            std::any::type_name::<T>(),
936            TypeId::of::<A>(),
937            validation,
938        )
939    }
940
941    /// Register an interface type.
942    ///
943    /// Returns an [`InterfaceRef`] that object builders use with
944    /// [`ObjectBuilder::implements`]. Interface fields have no resolvers: execution uses the
945    /// concrete object's field resolvers.
946    ///
947    /// Calling this again for the same name reopens the interface and adds fields.
948    pub fn interface(
949        &mut self,
950        name: impl Into<Name>,
951        build: impl FnOnce(&mut InterfaceBuilder<'_, Ctx>),
952    ) -> InterfaceRef {
953        let reference = self.interface_ref(name);
954        self.implement_interface(&reference, build);
955        reference
956    }
957
958    /// Create (or reopen) an interface whose GraphQL name may be computed at runtime.
959    ///
960    /// Use [`Schema::implement_interface`] to add fields. Calling this twice with the same name
961    /// reopens the same interface.
962    pub fn interface_ref(&mut self, name: impl Into<Name>) -> InterfaceRef {
963        let name = name.into();
964        self.validate_type_name("Interface", &name);
965        if !self.interfaces.contains_key(&name) {
966            self.interfaces.insert(
967                Arc::clone(&name),
968                gql::InterfaceType::new(Arc::clone(&name)),
969            );
970        }
971        InterfaceRef::new(name)
972    }
973
974    /// Add fields to an interface created by [`Schema::interface_ref`].
975    pub fn implement_interface(
976        &mut self,
977        reference: &InterfaceRef,
978        build: impl FnOnce(&mut InterfaceBuilder<'_, Ctx>),
979    ) -> &mut Self {
980        let name = Arc::clone(&reference.name);
981        if !self.interfaces.contains_key(&name) {
982            self.interfaces.insert(
983                Arc::clone(&name),
984                gql::InterfaceType::new(Arc::clone(&name)),
985            );
986        }
987        let existing = self.interfaces.shift_remove(&name);
988        let existing_auth_error = self.interface_auth_error.get(&*name).cloned();
989        let field_auth = self
990            .interface_field_auth
991            .shift_remove(&*name)
992            .unwrap_or_default();
993        let mut builder = InterfaceBuilder::<Ctx>::new(
994            existing,
995            field_auth,
996            existing_auth_error,
997            &mut self.registry,
998            name.clone(),
999        );
1000        build(&mut builder);
1001        let (interface, auth, auth_error, field_auth) = builder.finish();
1002        if let Some(message) = auth_error {
1003            self.interface_auth_error
1004                .insert(name.to_string(), Arc::clone(&message));
1005        }
1006        if auth.is_empty() {
1007            if let Some(message) = self.interface_auth_error.get(&*name).cloned() {
1008                if let Some(previous) = self
1009                    .interface_auth
1010                    .get_mut(&*name)
1011                    .and_then(|guards| guards.last_mut())
1012                {
1013                    *previous = previous.with_message(Some(message));
1014                }
1015            }
1016        } else {
1017            self.interface_auth
1018                .entry(name.to_string())
1019                .or_default()
1020                .extend(auth);
1021        }
1022        self.interface_field_auth
1023            .insert(name.to_string(), field_auth);
1024        self.interfaces.insert(name, interface);
1025        self
1026    }
1027
1028    /// Reopen an interface and add more fields to it.
1029    ///
1030    /// This is an alias for [`Schema::interface`].
1031    pub fn interface_fields(
1032        &mut self,
1033        name: impl Into<Name>,
1034        build: impl FnOnce(&mut InterfaceBuilder<'_, Ctx>),
1035    ) -> InterfaceRef {
1036        self.interface(name, build)
1037    }
1038
1039    /// Register a union type.
1040    ///
1041    /// Returns a [`UnionRef`] that fields can use with
1042    /// [`FieldConfig::as_abstract`], or that [`crate::UnionModel`] output types reference.
1043    /// Runtime type resolution relies on each object's generated `is_type_of` check, unless the
1044    /// union installs its own resolver with [`UnionBuilder::resolve_type`].
1045    ///
1046    /// Calling this again for the same name appends members.
1047    pub fn union(
1048        &mut self,
1049        name: impl Into<Name>,
1050        build: impl FnOnce(&mut UnionBuilder<Ctx>),
1051    ) -> UnionRef {
1052        let reference = self.union_ref(name);
1053        self.implement_union(&reference, build);
1054        reference
1055    }
1056
1057    /// Create (or reopen) a union whose GraphQL name may be computed at runtime.
1058    ///
1059    /// Use [`Schema::implement_union`] to declare members.
1060    pub fn union_ref(&mut self, name: impl Into<Name>) -> UnionRef {
1061        let name = name.into();
1062        self.validate_type_name("Union", &name);
1063        if !self.unions.contains_key(&name) {
1064            self.unions
1065                .insert(Arc::clone(&name), gql::UnionType::new(Arc::clone(&name)));
1066        }
1067        UnionRef::new(name)
1068    }
1069
1070    /// Add members to a union created by [`Schema::union_ref`].
1071    pub fn implement_union(
1072        &mut self,
1073        reference: &UnionRef,
1074        build: impl FnOnce(&mut UnionBuilder<Ctx>),
1075    ) -> &mut Self {
1076        let name = Arc::clone(&reference.name);
1077        if !self.unions.contains_key(&name) {
1078            self.unions
1079                .insert(Arc::clone(&name), gql::UnionType::new(Arc::clone(&name)));
1080        }
1081        let existing = self.unions.shift_remove(&name);
1082        let mut builder = UnionBuilder::<Ctx>::new(existing, name.clone(), &mut self.registry);
1083        build(&mut builder);
1084        let union = builder.finish();
1085        self.unions.insert(name, union);
1086        self
1087    }
1088
1089    /// Register a custom scalar explicitly.
1090    ///
1091    /// Scalars used by a field's input or output type are registered automatically; this is for
1092    /// scalars that are part of the public schema without appearing in a field signature.
1093    pub fn scalar<T: ScalarValue>(&mut self) -> &mut Self {
1094        self.registry.register_scalar::<T>();
1095        self
1096    }
1097
1098    /// Register an enum type explicitly.
1099    ///
1100    /// Enums used by a field's input or output type are registered automatically.
1101    pub fn enum_type<T: EnumModel>(&mut self) -> &mut Self {
1102        self.registry.register_enum::<T>();
1103        self
1104    }
1105
1106    /// Add query root fields.
1107    ///
1108    /// Every call appends, so a root can be declared from several modules.
1109    pub fn query(&mut self, build: impl FnOnce(&mut RootBuilder<'_, Ctx>)) -> &mut Self {
1110        let mut builder = RootBuilder::<Ctx>::new(
1111            &mut self.registry,
1112            &mut self.query,
1113            &mut self.checks,
1114            self.query_name.clone(),
1115        );
1116        build(&mut builder);
1117        self
1118    }
1119
1120    /// Add more query root fields. An alias for [`Schema::query`].
1121    pub fn query_fields(&mut self, build: impl FnOnce(&mut RootBuilder<'_, Ctx>)) -> &mut Self {
1122        self.query(build)
1123    }
1124
1125    /// Add mutation root fields. Every call appends.
1126    pub fn mutation(&mut self, build: impl FnOnce(&mut RootBuilder<'_, Ctx>)) -> &mut Self {
1127        let mut builder = RootBuilder::<Ctx>::new(
1128            &mut self.registry,
1129            &mut self.mutation,
1130            &mut self.checks,
1131            self.mutation_name.clone(),
1132        );
1133        build(&mut builder);
1134        self
1135    }
1136
1137    /// Add more mutation root fields. An alias for [`Schema::mutation`].
1138    pub fn mutation_fields(&mut self, build: impl FnOnce(&mut RootBuilder<'_, Ctx>)) -> &mut Self {
1139        self.mutation(build)
1140    }
1141
1142    /// Add subscription root fields. Every call appends.
1143    pub fn subscription(
1144        &mut self,
1145        build: impl FnOnce(&mut SubscriptionBuilder<'_, Ctx>),
1146    ) -> &mut Self {
1147        let mut builder = SubscriptionBuilder::<Ctx>::new(
1148            &mut self.registry,
1149            &mut self.subscription,
1150            &mut self.checks,
1151            self.subscription_name.clone(),
1152        );
1153        build(&mut builder);
1154        self
1155    }
1156
1157    /// Add more subscription root fields. An alias for [`Schema::subscription`].
1158    pub fn subscription_fields(
1159        &mut self,
1160        build: impl FnOnce(&mut SubscriptionBuilder<'_, Ctx>),
1161    ) -> &mut Self {
1162        self.subscription(build)
1163    }
1164
1165    /// Validate the schema and freeze it into a [`gql::Schema`].
1166    ///
1167    /// # Errors
1168    ///
1169    /// Returns every problem found: duplicate type names, fields that reference an object that
1170    /// was never registered, invalid interface implementations, and so on. See
1171    /// [`SchemaError`].
1172    pub fn build(self) -> Result<gql::Schema, SchemaError> {
1173        self.build_with(BuildOptions::default())
1174    }
1175
1176    /// Record a build error when a runtime type name is not a GraphQL name.
1177    fn validate_type_name(&mut self, kind: &str, name: &str) {
1178        if !is_valid_graphql_name(name) {
1179            self.errors.push(GraphQLError::new(format!(
1180                "{kind} type name \"{name}\" is not a valid GraphQL name. A name must match \
1181                 [_A-Za-z][_0-9A-Za-z]*."
1182            )));
1183        }
1184    }
1185
1186    /// Validate the schema with [`BuildOptions`] and freeze it into a [`gql::Schema`].
1187    ///
1188    /// `build_with` consumes the builder. Use [`Schema::build_clone`] when the builder is still
1189    /// needed, or call `schema.clone().build_with(options)`.
1190    #[cfg_attr(
1191        feature = "tracing",
1192        tracing::instrument(
1193            skip_all,
1194            level = "info",
1195            name = "gurafi.schema.build",
1196            fields(
1197                objects = self.objects.len(),
1198                interfaces = self.interfaces.len(),
1199                unions = self.unions.len(),
1200                plugins = self.plugins.len(),
1201                query_fields = self.query.len(),
1202                errors = tracing::field::Empty,
1203            )
1204        )
1205    )]
1206    pub fn build_with(mut self, options: BuildOptions) -> Result<gql::Schema, SchemaError> {
1207        let mut errors = std::mem::take(&mut self.errors);
1208        self.merge_generated_types(&mut errors);
1209        errors.extend(self.registry.take_errors());
1210        let has_unnamed_input = self.registry.has_unnamed_input();
1211
1212        for name in self.registry.referenced_objects() {
1213            if !self.objects.contains_key(name) {
1214                errors.push(GraphQLError::new(format!(
1215                    "Object type `{name}` is used by a field but was never registered. Call \
1216                     `schema.object::<...>(...)` or \
1217                     `schema.object_ref::<...>(\"{name}\")` before calling `build()`."
1218                )));
1219            }
1220        }
1221        for name in self.registry.referenced_unions() {
1222            if !self.unions.contains_key(name) {
1223                errors.push(GraphQLError::new(format!(
1224                    "Union type `{name}` is used by a field but was never registered. Call \
1225                     `schema.union(\"{name}\", ...)` before calling `build()`."
1226                )));
1227            }
1228        }
1229
1230        self.check_raw_field_mixing(&mut errors);
1231        self.expand_transitive_interfaces();
1232        self.resolve_inherited(&mut errors);
1233
1234        // Directive applications are stored by name until the type (or field or argument) they
1235        // refer to exists. Applying them here, after every declaration has been merged, means a
1236        // `type_directive` call may come before or after the type it names.
1237        let mut pending_type_directives = std::mem::take(&mut self.type_directives);
1238        self.apply_named_type_directives(&mut pending_type_directives);
1239        let argument_directives = std::mem::take(&mut self.argument_directives);
1240        self.apply_argument_directives(argument_directives, &mut errors);
1241        let input_field_directives = std::mem::take(&mut self.input_field_directives);
1242        self.apply_input_field_directives(input_field_directives, &mut errors);
1243
1244        // Plugins are installed before object- and interface-level authorization so those rules
1245        // stay outside the plugin chain. Taking the list out keeps the rest of the build free to
1246        // move the type maps.
1247        let plugins = std::mem::take(&mut self.plugins);
1248        apply_plugins(
1249            &plugins,
1250            PluginTargets {
1251                objects: &mut self.objects,
1252                interfaces: &mut self.interfaces,
1253                query: &mut self.query,
1254                mutation: &mut self.mutation,
1255                subscription: &mut self.subscription,
1256                query_name: &self.query_name,
1257                mutation_name: &self.mutation_name,
1258                subscription_name: &self.subscription_name,
1259            },
1260        );
1261        self.apply_guards();
1262
1263        let mut builder = gql::Schema::builder();
1264        if let Some(description) = self.description.clone() {
1265            builder = builder.description(description);
1266        }
1267        for definition in std::mem::take(&mut self.directive_definitions) {
1268            builder.add_directive(definition);
1269        }
1270
1271        let mut registry_types: Vec<(String, gql::Type)> =
1272            self.registry.into_types().into_iter().collect();
1273        let mut objects: Vec<(Name, gql::ObjectType)> = self.objects.into_iter().collect();
1274        let mut interfaces: Vec<(Name, gql::InterfaceType)> = self.interfaces.into_iter().collect();
1275        let mut unions: Vec<(Name, gql::UnionType)> = self.unions.into_iter().collect();
1276        if options.sort_types {
1277            registry_types.sort_by(|left, right| left.0.cmp(&right.0));
1278            objects.sort_by(|left, right| left.0.cmp(&right.0));
1279            interfaces.sort_by(|left, right| left.0.cmp(&right.0));
1280            unions.sort_by(|left, right| left.0.cmp(&right.0));
1281        }
1282        for (_, ty) in registry_types {
1283            builder.add_type(ty);
1284        }
1285        for (_, object) in objects {
1286            builder.add_type(gql::Type::from(object));
1287        }
1288        for (_, interface) in interfaces {
1289            builder.add_type(gql::Type::from(interface));
1290        }
1291        for (_, union) in unions {
1292            builder.add_type(gql::Type::from(union));
1293        }
1294
1295        if !self.query.is_empty() {
1296            let mut root = gql::ObjectType::new(self.query_name.clone());
1297            if let Some(description) = options.query_description.as_ref() {
1298                root = root.description(description.to_string());
1299            }
1300            for directive in pending_type_directives
1301                .shift_remove(self.query_name.as_str())
1302                .unwrap_or_default()
1303            {
1304                root = root.directive(directive);
1305            }
1306            for field in self.query {
1307                root = root.field(field);
1308            }
1309            builder.add_type(gql::Type::from(root));
1310            builder = builder.query(self.query_name.clone());
1311        }
1312        if !self.mutation.is_empty() {
1313            let mut root = gql::ObjectType::new(self.mutation_name.clone());
1314            if let Some(description) = options.mutation_description.as_ref() {
1315                root = root.description(description.to_string());
1316            }
1317            for directive in pending_type_directives
1318                .shift_remove(self.mutation_name.as_str())
1319                .unwrap_or_default()
1320            {
1321                root = root.directive(directive);
1322            }
1323            for field in self.mutation {
1324                root = root.field(field);
1325            }
1326            builder.add_type(gql::Type::from(root));
1327            builder = builder.mutation(self.mutation_name.clone());
1328        }
1329        if !self.subscription.is_empty() {
1330            let mut root = gql::ObjectType::new(self.subscription_name.clone());
1331            if let Some(description) = options.subscription_description.as_ref() {
1332                root = root.description(description.to_string());
1333            }
1334            for directive in pending_type_directives
1335                .shift_remove(self.subscription_name.as_str())
1336                .unwrap_or_default()
1337            {
1338                root = root.directive(directive);
1339            }
1340            for field in self.subscription {
1341                root = root.field(field);
1342            }
1343            builder.add_type(gql::Type::from(root));
1344            builder = builder.subscription(self.subscription_name.clone());
1345        }
1346
1347        for name in pending_type_directives.keys() {
1348            errors.push(GraphQLError::new(format!(
1349                "`Schema::type_directive` was called for `{name}`, but no type with that name was \
1350                 registered. Register the type with `object`, `object_ref`, `interface`, \
1351                 `union`, `scalar` or `enum_type`; a root operation type also needs at least one \
1352                 field."
1353            )));
1354        }
1355
1356        for plugin in &plugins {
1357            plugin.configure(&mut builder);
1358        }
1359
1360        match builder.build() {
1361            Ok(schema) => {
1362                validate_checks(&schema, &self.checks, &mut errors);
1363                if errors.is_empty() {
1364                    Ok(schema)
1365                } else {
1366                    Err(SchemaError::from_errors(errors))
1367                }
1368            }
1369            Err(error) => {
1370                // An unnamed nested input already has an actionable error above. `gql` also
1371                // reports the internal placeholder name; drop that follow-up instead of showing
1372                // users an implementation detail next to the real fix.
1373                errors.extend(error.into_errors().into_iter().filter(|error| {
1374                    !(has_unnamed_input && error.message().contains("__GurafiUnnamedInput"))
1375                }));
1376                Err(SchemaError::from_errors(errors))
1377            }
1378        }
1379    }
1380
1381    /// Build a schema from a clone, leaving this builder reusable.
1382    ///
1383    /// Registry state discovered while building is not written back to `self`, so declared
1384    /// types, fields and options are unchanged. This is what makes it possible to build the
1385    /// same schema twice, for example with different [`BuildOptions`].
1386    ///
1387    /// # Errors
1388    ///
1389    /// Same as [`Schema::build`].
1390    pub fn build_clone(&self) -> Result<gql::Schema, SchemaError> {
1391        self.clone().build()
1392    }
1393
1394    /// Attach pending directives to every named type that exists now.
1395    ///
1396    /// Root operation objects are created separately during the build, so they consume their
1397    /// entries from the same map after this runs.
1398    fn apply_named_type_directives(&mut self, pending: &mut IndexMap<Name, Vec<AppliedDirective>>) {
1399        for object in self.objects.values_mut() {
1400            if let Some(directives) = pending.shift_remove(object.name.as_ref()) {
1401                object.directives.extend(directives);
1402            }
1403        }
1404        for interface in self.interfaces.values_mut() {
1405            if let Some(directives) = pending.shift_remove(interface.name.as_ref()) {
1406                interface.directives.extend(directives);
1407            }
1408        }
1409        for union in self.unions.values_mut() {
1410            if let Some(directives) = pending.shift_remove(union.name.as_ref()) {
1411                union.directives.extend(directives);
1412            }
1413        }
1414        for ty in self.registry.types_mut().values_mut() {
1415            let Some(directives) = pending.shift_remove(ty.name().as_ref()) else {
1416                continue;
1417            };
1418            match ty {
1419                gql::Type::Scalar(scalar) => Arc::make_mut(scalar).directives.extend(directives),
1420                gql::Type::Object(object) => Arc::make_mut(object).directives.extend(directives),
1421                gql::Type::Interface(interface) => {
1422                    Arc::make_mut(interface).directives.extend(directives);
1423                }
1424                gql::Type::Union(union) => Arc::make_mut(union).directives.extend(directives),
1425                gql::Type::Enum(enumeration) => {
1426                    Arc::make_mut(enumeration).directives.extend(directives);
1427                }
1428                gql::Type::InputObject(input) => {
1429                    Arc::make_mut(input).directives.extend(directives);
1430                }
1431            }
1432        }
1433    }
1434
1435    /// Attach pending directives to field arguments.
1436    fn apply_argument_directives(
1437        &mut self,
1438        pending: Vec<(Name, Name, Name, AppliedDirective)>,
1439        errors: &mut Vec<GraphQLError>,
1440    ) {
1441        for (type_name, field_name, argument_name, directive) in pending {
1442            let Some(field) = self.field_mut(&type_name, &field_name) else {
1443                errors.push(GraphQLError::new(format!(
1444                    "`Schema::argument_directive` targets argument `{argument_name}` of field \
1445                     `{type_name}.{field_name}`, but that field does not exist. Declare the field \
1446                     before calling `build()`, or check the type and field names."
1447                )));
1448                continue;
1449            };
1450            let Some(argument) = field.args.get_mut(argument_name.as_ref()) else {
1451                errors.push(GraphQLError::new(format!(
1452                    "`Schema::argument_directive` targets `{type_name}.{field_name}({argument_name}:)`, \
1453                     but that field has no argument named `{argument_name}`. Arguments come from \
1454                     the resolver's args type."
1455                )));
1456                continue;
1457            };
1458            argument.directives.push(directive);
1459        }
1460    }
1461
1462    /// Attach pending directives to input object fields.
1463    fn apply_input_field_directives(
1464        &mut self,
1465        pending: Vec<(Name, Name, AppliedDirective)>,
1466        errors: &mut Vec<GraphQLError>,
1467    ) {
1468        for (type_name, field_name, directive) in pending {
1469            let input = self
1470                .registry
1471                .types_mut()
1472                .get_mut(type_name.as_ref())
1473                .and_then(|ty| match ty {
1474                    gql::Type::InputObject(input) => Some(Arc::make_mut(input)),
1475                    _ => None,
1476                });
1477            let Some(input) = input else {
1478                errors.push(GraphQLError::new(format!(
1479                    "`Schema::input_field_directive` targets `{type_name}.{field_name}`, but \
1480                     `{type_name}` is not a registered input object. Give the Rust type \
1481                     `#[graphql(name = \"{type_name}\")]` and use it as an argument or input field \
1482                     so it is registered before `build()`."
1483                )));
1484                continue;
1485            };
1486            let Some(field) = input.fields.get_mut(field_name.as_ref()) else {
1487                errors.push(GraphQLError::new(format!(
1488                    "`Schema::input_field_directive` targets `{type_name}.{field_name}`, but input \
1489                     object `{type_name}` has no field named `{field_name}`."
1490                )));
1491                continue;
1492            };
1493            field.directives.push(directive);
1494        }
1495    }
1496
1497    /// Find a field by its declaring type, including the root operation types.
1498    fn field_mut(&mut self, type_name: &str, field_name: &str) -> Option<&mut gql::Field> {
1499        if let Some(object) = self.objects.get_mut(type_name) {
1500            return object.fields.get_mut(field_name);
1501        }
1502        if let Some(interface) = self.interfaces.get_mut(type_name) {
1503            return interface.fields.get_mut(field_name);
1504        }
1505        let fields = if type_name == self.query_name {
1506            &mut self.query
1507        } else if type_name == self.mutation_name {
1508            &mut self.mutation
1509        } else if type_name == self.subscription_name {
1510            &mut self.subscription
1511        } else {
1512            return None;
1513        };
1514        fields
1515            .iter_mut()
1516            .find(|field| field.name.as_ref() == field_name)
1517    }
1518
1519    /// Merge objects and unions generated by result-union fields into the user-declared maps.
1520    ///
1521    /// The generated types are built while fields are declared, but plugins and authorization
1522    /// run on `objects` and `unions`, so they live in a side table until now. A generated name
1523    /// that collides with a user-declared type is reported rather than silently replacing it.
1524    fn merge_generated_types(&mut self, errors: &mut Vec<GraphQLError>) {
1525        let (objects, unions) = self.registry.take_generated();
1526        for (name, object) in objects {
1527            if self.objects.contains_key(name.as_ref()) {
1528                errors.push(GraphQLError::new(format!(
1529                    "Generated result-union success type `{name}` collides with an object type \
1530                     that is already registered. Give the field a different name, or register \
1531                     the generated type explicitly instead of using `field_result_union`."
1532                )));
1533                continue;
1534            }
1535            self.objects.insert(name, object);
1536        }
1537        for (name, union) in unions {
1538            if self.unions.contains_key(name.as_ref()) {
1539                errors.push(GraphQLError::new(format!(
1540                    "Generated result-union type `{name}` collides with a union type that is \
1541                     already registered. Give the field a different name, or register the \
1542                     generated type explicitly instead of using `field_result_union`."
1543                )));
1544                continue;
1545            }
1546            self.unions.insert(name, union);
1547        }
1548        for (name, error) in self.registry.take_required_objects() {
1549            if !self.objects.contains_key(name.as_str()) {
1550                errors.push(error);
1551            }
1552        }
1553    }
1554
1555    /// Add interfaces that are only implemented transitively.
1556    ///
1557    /// The specification requires an object that implements `Resource` to also declare every
1558    /// interface `Resource` implements (`Node`). Repeating that by hand is easy to forget, so the
1559    /// builder closes the relation before it hands the definitions to `gql`.
1560    fn expand_transitive_interfaces(&mut self) {
1561        let parents = interface_parents(&self.interfaces);
1562        for (name, interface) in &mut self.interfaces {
1563            let reachable = reachable_interfaces(&interface.interfaces, &parents);
1564            for parent in reachable {
1565                if parent.as_str() != name.as_ref()
1566                    && !interface
1567                        .interfaces
1568                        .iter()
1569                        .any(|existing| existing.as_ref() == parent.as_str())
1570                {
1571                    interface.interfaces.push(Arc::from(parent));
1572                }
1573            }
1574        }
1575        let parents = interface_parents(&self.interfaces);
1576        for object in self.objects.values_mut() {
1577            let reachable = reachable_interfaces(&object.interfaces, &parents);
1578            for name in reachable {
1579                if !object
1580                    .interfaces
1581                    .iter()
1582                    .any(|existing| existing.as_ref() == name.as_str())
1583                {
1584                    object.interfaces.push(Arc::from(name));
1585                }
1586            }
1587        }
1588    }
1589
1590    /// Reject objects that mix raw fields with resolver-backed fields.
1591    ///
1592    /// A raw object is resolved as a whole, so its parent value is an object map. A
1593    /// resolver-backed field on the same object would be handed that map where its resolver
1594    /// expects the Rust model, which only fails later, per request, with an internal error.
1595    fn check_raw_field_mixing(&self, errors: &mut Vec<GraphQLError>) {
1596        for (object_name, raw_fields) in &self.raw_fields {
1597            if raw_fields.is_empty() {
1598                continue;
1599            }
1600            let Some(object) = self.objects.get(object_name) else {
1601                continue;
1602            };
1603            for field in object.fields.values() {
1604                if raw_fields.contains(&field.name) {
1605                    continue;
1606                }
1607                errors.push(GraphQLError::new(format!(
1608                    "Object `{object_name}` mixes raw fields with resolver-backed field `{}`. A \
1609                     raw object is resolved as a whole, so that resolver would receive a raw \
1610                     object map where it expects the `{object_name}` model. Declare every field \
1611                     with `raw_field`/`raw_field_with`, or give every field a resolver.",
1612                    field.name,
1613                )));
1614            }
1615        }
1616    }
1617
1618    /// Rewrite fields declared with [`ObjectBuilder::resolve_inherited`] from the matching
1619    /// interface field.
1620    fn resolve_inherited(&mut self, errors: &mut Vec<GraphQLError>) {
1621        let parents = interface_parents(&self.interfaces);
1622        for pending in std::mem::take(&mut self.pending_inherited) {
1623            let Some(object) = self.objects.get(pending.object.as_ref()) else {
1624                errors.push(GraphQLError::new(format!(
1625                    "Object `{}` was not registered, but field `{}` inherits from an interface.",
1626                    pending.object, pending.field
1627                )));
1628                continue;
1629            };
1630            let reachable = reachable_interfaces(&object.interfaces, &parents);
1631            let mut source = None;
1632            for interface_name in &reachable {
1633                let Some(interface) = self.interfaces.get(interface_name.as_str()) else {
1634                    continue;
1635                };
1636                if let Some(field) = interface.fields.get(&pending.field) {
1637                    source = Some((field.clone(), interface_name.clone()));
1638                    break;
1639                }
1640            }
1641            let Some((interface_field, interface_name)) = source else {
1642                errors.push(GraphQLError::new(format!(
1643                    "Object `{}` declares field `{}` with `resolve_inherited`, but no implemented \
1644                     interface has that field. Declare it on an interface with \
1645                     `interface.field(...)`, or use `field` to give the object its own type.",
1646                    pending.object, pending.field
1647                )));
1648                continue;
1649            };
1650            let interface_ty = interface_field.ty.clone();
1651            let interface_args = interface_field.args.clone();
1652            if pending.expected_args.len() != interface_args.len()
1653                || pending
1654                    .expected_args
1655                    .iter()
1656                    .any(|(name, ty)| interface_args.get(name).is_none_or(|arg| arg.ty != *ty))
1657            {
1658                errors.push(GraphQLError::new(format!(
1659                    "Object field `{}.{}` inherits from `{}.{}`, but its resolver's arguments do \
1660                     not match. Declare an args type with the same argument names and types as the \
1661                     interface field.",
1662                    pending.object, pending.field, interface_name, pending.field
1663                )));
1664                continue;
1665            }
1666
1667            let object = self
1668                .objects
1669                .get_mut(pending.object.as_ref())
1670                .expect("the object was checked above");
1671            let Some(field) = object.fields.get_mut(&pending.field) else {
1672                continue;
1673            };
1674            let actual = field.ty.clone();
1675            self.checks.push(FieldCheck::InheritedType {
1676                owner: Arc::clone(&pending.object),
1677                field: pending.field.clone(),
1678                actual,
1679                expected: interface_ty.clone(),
1680            });
1681            field.ty = interface_ty;
1682            field.args = interface_args;
1683            if field.description.is_none() {
1684                field.description = interface_field.description;
1685            }
1686            if field.deprecation_reason.is_none() {
1687                field.deprecation_reason = interface_field.deprecation_reason;
1688            }
1689            for directive in interface_field.directives {
1690                if !field
1691                    .directives
1692                    .iter()
1693                    .any(|existing| existing.name == directive.name)
1694                {
1695                    field.directives.push(directive);
1696                }
1697            }
1698        }
1699    }
1700
1701    /// Apply object- and interface-level authorization to every affected field.
1702    fn apply_guards(&mut self) {
1703        let parents = interface_parents(&self.interfaces);
1704        for (object_name, object) in &mut self.objects {
1705            let reachable = reachable_interfaces(&object.interfaces, &parents);
1706            let object_guards = self.object_auth.get(object_name.as_ref()).cloned();
1707            for field in object.fields.values_mut() {
1708                if let Some(guards) = &object_guards {
1709                    for guard in guards {
1710                        apply_auth_guard(field, Arc::clone(guard));
1711                    }
1712                }
1713                for interface_name in &reachable {
1714                    if let Some(guards) = self.interface_auth.get(interface_name.as_str()) {
1715                        for guard in guards {
1716                            apply_auth_guard(field, Arc::clone(guard));
1717                        }
1718                    }
1719                    if let Some(guard) = self
1720                        .interface_field_auth
1721                        .get(interface_name.as_str())
1722                        .and_then(|fields| fields.get(&field.name))
1723                    {
1724                        apply_auth_guard(field, Arc::clone(guard));
1725                    }
1726                }
1727            }
1728        }
1729    }
1730}
1731
1732/// The direct super-interfaces of every registered interface, keyed by name.
1733fn interface_parents(
1734    interfaces: &IndexMap<Name, gql::InterfaceType>,
1735) -> HashMap<String, Vec<String>> {
1736    interfaces
1737        .iter()
1738        .map(|(name, interface)| {
1739            (
1740                name.to_string(),
1741                interface
1742                    .interfaces
1743                    .iter()
1744                    .map(|parent| parent.to_string())
1745                    .collect(),
1746            )
1747        })
1748        .collect()
1749}
1750
1751/// Interface names implemented by `direct` and by the interfaces those interfaces implement.
1752fn reachable_interfaces(direct: &[Name], parents: &HashMap<String, Vec<String>>) -> Vec<String> {
1753    let mut result = Vec::new();
1754    let mut pending: Vec<String> = direct.iter().map(|name| name.to_string()).collect();
1755    while let Some(name) = pending.pop() {
1756        if result.contains(&name) {
1757            continue;
1758        }
1759        if let Some(parents) = parents.get(&name) {
1760            pending.extend(parents.iter().cloned());
1761        }
1762        result.push(name);
1763    }
1764    result
1765}
1766
1767fn new_object<M: ObjectModel>() -> gql::ObjectType {
1768    let mut object = gql::ObjectType::new(M::NAME);
1769    if let Some(description) = M::description() {
1770        object = object.description(description);
1771    }
1772    object.is_type_of(|value| value.as_external::<M>().is_some())
1773}
1774
1775/// Builder for one object type, received by [`Schema::object`].
1776pub struct ObjectBuilder<'a, Ctx: 'static, M: ObjectModel> {
1777    registry: &'a mut TypeRegistry,
1778    object: gql::ObjectType,
1779    checks: &'a mut Vec<FieldCheck>,
1780    pending_inherited: &'a mut Vec<PendingInherited>,
1781    raw_fields: &'a mut HashSet<Name>,
1782    auth: Vec<Arc<AuthGuard<Ctx>>>,
1783    auth_error: Option<Arc<str>>,
1784    marker: PhantomData<fn() -> (Ctx, M)>,
1785}
1786
1787impl<'a, Ctx: 'static, M: ObjectModel> ObjectBuilder<'a, Ctx, M> {
1788    fn new(
1789        existing: Option<gql::ObjectType>,
1790        existing_auth_error: Option<Arc<str>>,
1791        registry: &'a mut TypeRegistry,
1792        checks: &'a mut Vec<FieldCheck>,
1793        pending_inherited: &'a mut Vec<PendingInherited>,
1794        raw_fields: &'a mut HashSet<Name>,
1795        name: Name,
1796    ) -> Self {
1797        let object = existing.unwrap_or_else(|| {
1798            let mut object = gql::ObjectType::new(name);
1799            if let Some(description) = M::description() {
1800                object = object.description(description);
1801            }
1802            object.is_type_of(|value| value.as_external::<M>().is_some())
1803        });
1804        Self {
1805            registry,
1806            object,
1807            checks,
1808            pending_inherited,
1809            raw_fields,
1810            auth: Vec::new(),
1811            auth_error: existing_auth_error,
1812            marker: PhantomData,
1813        }
1814    }
1815
1816    fn finish(self) -> (gql::ObjectType, Vec<Arc<AuthGuard<Ctx>>>, Option<Arc<str>>) {
1817        (self.object, self.auth, self.auth_error)
1818    }
1819
1820    /// Set the object's description, overriding the one from the derive.
1821    pub fn description(&mut self, description: impl Into<Arc<str>>) -> &mut Self {
1822        self.object.description = Some(description.into());
1823        self
1824    }
1825
1826    /// Apply a directive to this object type.
1827    ///
1828    /// Each call adds an application in declaration order, which is how a repeatable directive
1829    /// is used more than once. The application is checked against its definition when the schema
1830    /// is built; see [`Schema::directive`].
1831    pub fn directive(&mut self, directive: AppliedDirective) -> &mut Self {
1832        self.object.directives.push(directive);
1833        self
1834    }
1835
1836    /// Whether this object already declares a field with `name`.
1837    ///
1838    /// This is a read-only inspection for extensions that add a field only when the object has
1839    /// not declared it yet (for example a Relay `id` field). It never changes the definition.
1840    #[must_use]
1841    pub fn has_field(&self, name: &str) -> bool {
1842        self.object
1843            .fields
1844            .keys()
1845            .any(|field| field.as_ref() == name)
1846    }
1847
1848    /// Declare that this object implements an interface.
1849    ///
1850    /// Both `node` and `&node` are accepted, so a reference can be reused without cloning.
1851    pub fn implements(&mut self, interface: impl Into<InterfaceRef>) -> &mut Self {
1852        let interface = interface.into();
1853        let name: Name = Arc::from(interface.name());
1854        if !self
1855            .object
1856            .interfaces
1857            .iter()
1858            .any(|existing| **existing == *name)
1859        {
1860            self.object.interfaces.push(name);
1861        }
1862        self
1863    }
1864
1865    /// Require every field of this object to satisfy `predicate`.
1866    ///
1867    /// The check is applied to fields declared in every `object`/`object_fields` call for this
1868    /// model, including calls in other modules, and to fields added through
1869    /// [`ObjectBuilder::resolve_inherited`]. Declaring another rule on a reopened object composes
1870    /// with the existing one (all rules must allow); it never replaces an earlier rule. A denial
1871    /// follows normal null propagation.
1872    pub fn auth(&mut self, predicate: impl Fn(&Ctx) -> bool + Send + Sync + 'static) -> &mut Self {
1873        self.auth
1874            .push(crate::field::sync_guard(predicate, self.auth_error.clone()));
1875        self
1876    }
1877
1878    /// Like [`ObjectBuilder::auth`], but the predicate is asynchronous.
1879    pub fn auth_async(
1880        &mut self,
1881        predicate: impl for<'r> Fn(&'r Ctx) -> BoxFuture<'r, bool> + Send + Sync + 'static,
1882    ) -> &mut Self {
1883        self.auth.push(crate::field::async_guard(
1884            predicate,
1885            self.auth_error.clone(),
1886        ));
1887        self
1888    }
1889
1890    /// Set the message returned when the object-level authorization denies access.
1891    pub fn auth_error(&mut self, message: impl Into<Arc<str>>) -> &mut Self {
1892        self.auth_error = Some(message.into());
1893        if let Some(auth) = self.auth.last_mut() {
1894            *auth = auth.with_message(self.auth_error.clone());
1895        }
1896        self
1897    }
1898
1899    /// Expose a model property as a field.
1900    ///
1901    /// The field name and type are inferred by `gurafi::expose!`.
1902    ///
1903    /// The accessor is installed as a synchronous property resolver: execution calls it inline,
1904    /// without boxing a future, on both the leaf fast path and the general completion path. Field
1905    /// options that need a future (`auth`, `auth_async`, `validate` or a plugin that wraps
1906    /// `resolve`) convert the field to the boxed path once, when the option is applied.
1907    pub fn expose<T>(&mut self, expose: Expose<M, T>) -> FieldConfig<'_, Ctx>
1908    where
1909        T: OutputType + IntoValue + Send + 'static,
1910    {
1911        let (name, get) = expose.into_parts();
1912        let field = gql::Field::new(name, T::output_type()).sync_resolve(move |context| {
1913            let model = model_ref::<M>(context.parent, context.parent_type, context.field_name)?;
1914            (get)(model).into_value()
1915        });
1916        let mut config = self.push(
1917            field,
1918            T::is_optional(),
1919            std::any::type_name::<T>(),
1920            TypeId::of::<()>(),
1921            ValidationSlot::new(),
1922        );
1923        config.defer_output::<T>();
1924        config
1925    }
1926
1927    /// Declare a field that is read from a raw object map instead of a resolver.
1928    ///
1929    /// No resolver is installed. When the parent value is the object map produced by
1930    /// [`Raw::object`](crate::Raw::object), execution reads the field with the same name using
1931    /// the executor's default property lookup. This is the object-side counterpart to
1932    /// [`Raw`](crate::Raw): declare every field of an object this way when the object is
1933    /// resolved as a whole.
1934    ///
1935    /// ```
1936    /// use gurafi::{NoArgs, Object, Raw, RawObject, Schema};
1937    ///
1938    /// struct Ctx;
1939    ///
1940    /// #[derive(Object)]
1941    /// struct Giraffe {
1942    ///     name: String,
1943    /// }
1944    ///
1945    /// let mut schema = Schema::<Ctx>::new();
1946    /// schema.object::<Giraffe>(|o| {
1947    ///     o.raw_field::<String>("name");
1948    /// });
1949    /// schema.query(|q| {
1950    ///     q.field("giraffe", |_: NoArgs, _: &Ctx| {
1951    ///         Raw::<Giraffe>::object(RawObject::new().field("name", "Melman").build())
1952    ///     });
1953    /// });
1954    /// # let _ = schema.build().expect("valid schema");
1955    /// ```
1956    ///
1957    /// The type comes from `T`, so the declared GraphQL type is still checked against the rest
1958    /// of the schema. The value in the map is not: a missing non-null field or a wrong-typed
1959    /// field is an execution-time error, not a build error. An object that declares a raw field
1960    /// may not also declare a resolver-backed field; the build rejects the mix because the
1961    /// resolver would receive a raw object map where it expects the Rust model.
1962    ///
1963    /// `raw_field` has no arguments. To implement an interface field that takes arguments (or to
1964    /// have the executor coerce and validate arguments for a concrete raw field), use
1965    /// [`ObjectBuilder::raw_field_with`]. A `validate` hook on `raw_field` is a build error, since
1966    /// there is no resolver in which it could run.
1967    ///
1968    /// The map itself is trusted: object keys are read by name, and reserved `__gql_*` keys are
1969    /// ignored by [`crate::RawObject`] and removed by [`crate::Raw::new`]. Untrusted data must go
1970    /// through one of those constructors, never through an arbitrary `gql::Value::Object`.
1971    pub fn raw_field<T: OutputType>(&mut self, name: &'static str) -> FieldConfig<'_, Ctx> {
1972        T::register_output(self.registry);
1973        self.raw_fields.insert(Arc::from(name));
1974        let field = gql::Field::new(name, T::output_type());
1975        self.push(
1976            field,
1977            T::is_optional(),
1978            std::any::type_name::<T>(),
1979            TypeId::of::<RawFieldArgs>(),
1980            ValidationSlot::new(),
1981        )
1982    }
1983
1984    /// Declare a raw field with arguments, read from the raw object map by name.
1985    ///
1986    /// This is [`ObjectBuilder::raw_field`] plus `A`'s argument declarations. The executor
1987    /// coerces and validates the arguments through a normal resolver, then reads the field value
1988    /// from the parent object map. Use it for an interface field that takes arguments, or when a
1989    /// concrete raw field needs argument coercion:
1990    ///
1991    /// ```
1992    /// use gurafi::{Input, NoArgs, Object, Raw, RawObject, Schema};
1993    ///
1994    /// struct Ctx;
1995    ///
1996    /// #[derive(Object)]
1997    /// struct Giraffe {
1998    ///     name: String,
1999    /// }
2000    ///
2001    /// #[derive(Input)]
2002    /// struct PictureArgs {
2003    ///     width: i32,
2004    /// }
2005    ///
2006    /// let mut schema = Schema::<Ctx>::new();
2007    /// schema.object::<Giraffe>(|o| {
2008    ///     o.raw_field_with::<String, PictureArgs>("picture");
2009    /// });
2010    /// schema.query(|q| {
2011    ///     q.field("giraffe", |_: NoArgs, _: &Ctx| {
2012    ///         Raw::<Giraffe>::object(
2013    ///             RawObject::new().field("picture", "wide.jpg").build(),
2014    ///         )
2015    ///     });
2016    /// });
2017    /// # let _ = schema.build().expect("valid schema");
2018    /// ```
2019    ///
2020    /// A `validate` hook is run once per resolution, just as it is on a resolver-backed field.
2021    /// Authorization installs a guard around the same resolver.
2022    pub fn raw_field_with<T: OutputType, A: InputObject>(
2023        &mut self,
2024        name: &'static str,
2025    ) -> FieldConfig<'_, Ctx> {
2026        T::register_output(self.registry);
2027        A::register_args(self.registry);
2028        self.raw_fields.insert(Arc::from(name));
2029        let validation = ValidationSlot::new();
2030        let hook = validation.clone();
2031        let field_name = name;
2032        let field = add_arguments::<A>(gql::Field::new(name, T::output_type()), self.registry)
2033            .resolve(move |context| {
2034                let hook = hook.clone();
2035                Box::pin(async move {
2036                    let args = coerce_args::<A>(
2037                        context.args,
2038                        context.info.parent_type,
2039                        context.info.field_name,
2040                    )?;
2041                    if hook.is_installed() {
2042                        let ctx = context.context.require_data::<Ctx>()?;
2043                        hook.run(&args, ctx)?;
2044                    }
2045                    read_raw_field(field_name, context.parent)
2046                })
2047            });
2048        self.push(
2049            field,
2050            T::is_optional(),
2051            std::any::type_name::<T>(),
2052            TypeId::of::<A>(),
2053            validation,
2054        )
2055    }
2056
2057    /// Add a synchronous field whose resolver cannot fail.
2058    pub fn field<T, A, F>(&mut self, name: &'static str, resolver: F) -> FieldConfig<'_, Ctx>
2059    where
2060        T: OutputType + IntoValue + Send + 'static,
2061        A: InputObject,
2062        F: Fn(&M, A, &Ctx) -> T + Send + Sync + 'static,
2063    {
2064        self.field_with_info::<T, A, _>(name, move |model: &M, args: A, ctx: &Ctx, _| {
2065            resolver(model, args, ctx)
2066        })
2067    }
2068
2069    /// Add a synchronous field whose output type is a runtime-named object.
2070    ///
2071    /// `reference` supplies the GraphQL name; `T` supplies the list and nullability wrappers,
2072    /// just as [`FieldConfig::as_object_ref`] does. The resolver returns the object's model (or a
2073    /// [`crate::Raw`] of it), so `T`'s named type should be the model the reference was created
2074    /// for.
2075    ///
2076    /// ```
2077    /// # use gurafi::{NoArgs, Object, Schema};
2078    /// # struct Ctx;
2079    /// #[derive(Object)]
2080    /// struct User { name: String }
2081    ///
2082    /// let mut schema = Schema::<Ctx>::new();
2083    /// let admin = schema.object_ref::<User>("AdminUser");
2084    /// schema.implement(&admin, |o| {
2085    ///     o.expose(gurafi::expose!(User::name));
2086    /// });
2087    /// schema.object::<User>(|o| {
2088    ///     o.field_ref(&admin, "bestFriend", |_: &User, _: NoArgs, _: &Ctx| User {
2089    ///         name: "ada".into(),
2090    ///     });
2091    ///     o.field_ref::<Vec<User>, NoArgs, _, _>(
2092    ///         &admin,
2093    ///         "friends",
2094    ///         |_: &User, _: NoArgs, _: &Ctx| vec![User { name: "ada".into() }],
2095    ///     )
2096    ///     .nullable_items();
2097    /// });
2098    /// # let _ = schema;
2099    /// ```
2100    pub fn field_ref<T, A, F, N>(
2101        &mut self,
2102        reference: &ObjectRef<N>,
2103        name: &'static str,
2104        resolver: F,
2105    ) -> FieldConfig<'_, Ctx>
2106    where
2107        N: ObjectModel,
2108        T: OutputType + IntoValue + Send + 'static,
2109        A: InputObject,
2110        F: Fn(&M, A, &Ctx) -> T + Send + Sync + 'static,
2111    {
2112        let (field, validation) = object_field_with_info::<M, Ctx, T, A, _>(
2113            name,
2114            move |model: &M, args: A, ctx: &Ctx, _| resolver(model, args, ctx),
2115            self.registry,
2116            false,
2117        );
2118        let mut config = self.push(
2119            field,
2120            T::is_optional(),
2121            std::any::type_name::<T>(),
2122            TypeId::of::<A>(),
2123            validation,
2124        );
2125        config.as_object_ref(reference);
2126        config
2127    }
2128
2129    /// Add a synchronous field with an explicitly built runtime type reference.
2130    ///
2131    /// Use this for runtime-named interfaces and unions, or for arbitrary wrapper combinations
2132    /// (`TypeRef::named(name).list().non_null()`). `T` still supplies the Rust type used to
2133    /// check that the declared wrappers are truthful.
2134    pub fn field_ref_type<T, A, F>(
2135        &mut self,
2136        ty: TypeRef,
2137        name: &'static str,
2138        resolver: F,
2139    ) -> FieldConfig<'_, Ctx>
2140    where
2141        T: OutputType + IntoValue + Send + 'static,
2142        A: InputObject,
2143        F: Fn(&M, A, &Ctx) -> T + Send + Sync + 'static,
2144    {
2145        let (field, validation) = object_field_with_info::<M, Ctx, T, A, _>(
2146            name,
2147            move |model: &M, args: A, ctx: &Ctx, _| resolver(model, args, ctx),
2148            self.registry,
2149            false,
2150        );
2151        let mut config = self.push(
2152            field,
2153            T::is_optional(),
2154            std::any::type_name::<T>(),
2155            TypeId::of::<A>(),
2156            validation,
2157        );
2158        config.as_dynamic(ty);
2159        config
2160    }
2161
2162    /// Add a synchronous field whose resolver also receives the [`gql::ResolveInfo`].
2163    ///
2164    /// The info exposes the field name, parent type, return type, response path and schema, plus
2165    /// the merged field nodes, operation, fragments, root value and coerced variables. A resolver
2166    /// can therefore inspect the selected sub-fields, for example to build a projection or batch a
2167    /// loader by selection.
2168    pub fn field_with_info<T, A, F>(
2169        &mut self,
2170        name: &'static str,
2171        resolver: F,
2172    ) -> FieldConfig<'_, Ctx>
2173    where
2174        T: OutputType + IntoValue + Send + 'static,
2175        A: InputObject,
2176        F: for<'r> Fn(&'r M, A, &'r Ctx, &'r gql::ResolveInfo<'r>) -> T + Send + Sync + 'static,
2177    {
2178        let (field, validation) =
2179            object_field_with_info::<M, Ctx, T, A, F>(name, resolver, self.registry, true);
2180        self.push(
2181            field,
2182            T::is_optional(),
2183            std::any::type_name::<T>(),
2184            TypeId::of::<A>(),
2185            validation,
2186        )
2187    }
2188
2189    /// Add a synchronous field whose resolver returns a `Result`.
2190    pub fn field_result<T, A, F>(&mut self, name: &'static str, resolver: F) -> FieldConfig<'_, Ctx>
2191    where
2192        T: OutputType + IntoValue + Send + 'static,
2193        A: InputObject,
2194        F: Fn(&M, A, &Ctx) -> Result<T, GraphQLError> + Send + Sync + 'static,
2195    {
2196        self.field_result_with_info::<T, A, _>(name, move |model: &M, args: A, ctx: &Ctx, _| {
2197            resolver(model, args, ctx)
2198        })
2199    }
2200
2201    /// Add a synchronous fallible field whose resolver also receives the [`gql::ResolveInfo`].
2202    pub fn field_result_with_info<T, A, F>(
2203        &mut self,
2204        name: &'static str,
2205        resolver: F,
2206    ) -> FieldConfig<'_, Ctx>
2207    where
2208        T: OutputType + IntoValue + Send + 'static,
2209        A: InputObject,
2210        F: for<'r> Fn(&'r M, A, &'r Ctx, &'r gql::ResolveInfo<'r>) -> Result<T, GraphQLError>
2211            + Send
2212            + Sync
2213            + 'static,
2214    {
2215        let (field, validation) =
2216            object_field_result_with_info::<M, Ctx, T, A, F>(name, resolver, self.registry);
2217        self.push(
2218            field,
2219            T::is_optional(),
2220            std::any::type_name::<T>(),
2221            TypeId::of::<A>(),
2222            validation,
2223        )
2224    }
2225
2226    /// Add a synchronous field whose resolver returns a typed `Result`.
2227    ///
2228    /// Unlike [`ObjectBuilder::field_result`], the failure value is part of the schema: the
2229    /// field returns a generated `<Parent><Field>Result` union whose members are a
2230    /// `<Parent><Field>Success` payload (`data: T`) and each variant of `E`'s object type. This
2231    /// is the Pothos Errors pattern: a client can select error payload fields instead of only
2232    /// reading a message from the GraphQL `errors` array.
2233    ///
2234    /// `E` is declared with `#[derive(ErrorUnion)]`; its payload objects must still be
2235    /// registered with `schema.object::<M>(...)`, otherwise the build reports the missing type.
2236    /// The generated names come from the object's actual GraphQL name (including a
2237    /// [`Schema::object_ref`] runtime name) and the field name, PascalCased.
2238    ///
2239    /// ```
2240    /// use gurafi::{ErrorUnion, NoArgs, Object, Schema};
2241    ///
2242    /// struct Ctx;
2243    ///
2244    /// #[derive(Object)]
2245    /// struct User {
2246    ///     name: String,
2247    /// }
2248    ///
2249    /// #[derive(Object)]
2250    /// struct ConflictError {
2251    ///     message: String,
2252    /// }
2253    ///
2254    /// #[derive(ErrorUnion)]
2255    /// enum CreateUserError {
2256    ///     Conflict(ConflictError),
2257    /// }
2258    ///
2259    /// let mut schema = Schema::<Ctx>::new();
2260    /// schema.object::<User>(|o| {
2261    ///     o.field("name", |u: &User, _: NoArgs, _: &Ctx| u.name.clone());
2262    /// });
2263    /// schema.object::<ConflictError>(|o| {
2264    ///     o.field("message", |e: &ConflictError, _: NoArgs, _: &Ctx| e.message.clone());
2265    /// });
2266    /// schema.query(|q| {
2267    ///     q.field("ok", |_: NoArgs, _: &Ctx| true);
2268    /// });
2269    /// schema.mutation(|m| {
2270    ///     m.field_result_union::<User, CreateUserError, NoArgs, _>(
2271    ///         "createUser",
2272    ///         |_: NoArgs, _: &Ctx| {
2273    ///             Ok(User { name: "ada".into() })
2274    ///         },
2275    ///     );
2276    /// });
2277    /// // `Mutation.createUser: MutationCreateUserResult!`
2278    /// //   `type MutationCreateUserSuccess { data: User! }`
2279    /// //   `union MutationCreateUserResult = MutationCreateUserSuccess | ConflictError`
2280    /// let schema = schema.build().expect("valid schema");
2281    /// # let _ = schema;
2282    /// ```
2283    pub fn field_result_union<T, E, A, F>(
2284        &mut self,
2285        name: &'static str,
2286        resolver: F,
2287    ) -> FieldConfig<'_, Ctx>
2288    where
2289        T: OutputType + IntoValue + Send + 'static,
2290        E: ErrorUnionModel,
2291        A: InputObject,
2292        F: Fn(&M, A, &Ctx) -> core::result::Result<T, E> + Send + Sync + 'static,
2293    {
2294        self.field_result_union_with_info::<T, E, A, _>(
2295            name,
2296            move |model: &M, args: A, ctx: &Ctx, _| resolver(model, args, ctx),
2297        )
2298    }
2299
2300    /// Add a synchronous typed-result field whose resolver also receives [`gql::ResolveInfo`].
2301    pub fn field_result_union_with_info<T, E, A, F>(
2302        &mut self,
2303        name: &'static str,
2304        resolver: F,
2305    ) -> FieldConfig<'_, Ctx>
2306    where
2307        T: OutputType + IntoValue + Send + 'static,
2308        E: ErrorUnionModel,
2309        A: InputObject,
2310        F: for<'r> Fn(&'r M, A, &'r Ctx, &'r gql::ResolveInfo<'r>) -> core::result::Result<T, E>
2311            + Send
2312            + Sync
2313            + 'static,
2314    {
2315        let parent = Arc::clone(&self.object.name);
2316        let (field, validation) = object_field_result_union_with_info::<M, Ctx, T, E, A, F>(
2317            name,
2318            resolver,
2319            self.registry,
2320            &parent,
2321        );
2322        self.push(
2323            field,
2324            false,
2325            std::any::type_name::<T>(),
2326            TypeId::of::<A>(),
2327            validation,
2328        )
2329    }
2330
2331    /// Add an asynchronous typed-result field.
2332    ///
2333    /// This is the async form of [`ObjectBuilder::field_result_union`]. The resolver returns a
2334    /// boxed future, written as `Box::pin(async move { ... })`, exactly like the other async
2335    /// resolver variants.
2336    pub fn field_result_union_async<T, E, A, F>(
2337        &mut self,
2338        name: &'static str,
2339        resolver: F,
2340    ) -> FieldConfig<'_, Ctx>
2341    where
2342        T: OutputType + IntoValue + Send + 'static,
2343        E: ErrorUnionModel,
2344        A: InputObject,
2345        F: for<'r> Fn(&'r M, A, &'r Ctx) -> BoxFuture<'r, core::result::Result<T, E>>
2346            + Send
2347            + Sync
2348            + 'static,
2349    {
2350        self.field_result_union_async_with_info::<T, E, A, _>(
2351            name,
2352            move |model: &M, args: A, ctx: &Ctx, _| resolver(model, args, ctx),
2353        )
2354    }
2355
2356    /// Add an asynchronous typed-result field whose resolver also receives
2357    /// [`gql::ResolveInfo`].
2358    pub fn field_result_union_async_with_info<T, E, A, F>(
2359        &mut self,
2360        name: &'static str,
2361        resolver: F,
2362    ) -> FieldConfig<'_, Ctx>
2363    where
2364        T: OutputType + IntoValue + Send + 'static,
2365        E: ErrorUnionModel,
2366        A: InputObject,
2367        F: for<'r> Fn(
2368                &'r M,
2369                A,
2370                &'r Ctx,
2371                &'r gql::ResolveInfo<'r>,
2372            ) -> BoxFuture<'r, core::result::Result<T, E>>
2373            + Send
2374            + Sync
2375            + 'static,
2376    {
2377        let parent = Arc::clone(&self.object.name);
2378        let (field, validation) = object_field_result_union_async_with_info::<M, Ctx, T, E, A, F>(
2379            name,
2380            resolver,
2381            self.registry,
2382            &parent,
2383        );
2384        self.push(
2385            field,
2386            false,
2387            std::any::type_name::<T>(),
2388            TypeId::of::<A>(),
2389            validation,
2390        )
2391    }
2392
2393    /// Add an asynchronous field whose resolver cannot fail.
2394    ///
2395    /// The resolver returns a boxed future, written as `Box::pin(async move { ... })`.
2396    pub fn field_async<T, A, F>(&mut self, name: &'static str, resolver: F) -> FieldConfig<'_, Ctx>
2397    where
2398        T: OutputType + IntoValue + Send + 'static,
2399        A: InputObject,
2400        F: for<'r> Fn(&'r M, A, &'r Ctx) -> BoxFuture<'r, T> + Send + Sync + 'static,
2401    {
2402        self.field_async_with_info::<T, A, _>(name, move |model: &M, args: A, ctx: &Ctx, _| {
2403            resolver(model, args, ctx)
2404        })
2405    }
2406
2407    /// Add an asynchronous field whose resolver also receives the [`gql::ResolveInfo`].
2408    pub fn field_async_with_info<T, A, F>(
2409        &mut self,
2410        name: &'static str,
2411        resolver: F,
2412    ) -> FieldConfig<'_, Ctx>
2413    where
2414        T: OutputType + IntoValue + Send + 'static,
2415        A: InputObject,
2416        F: for<'r> Fn(&'r M, A, &'r Ctx, &'r gql::ResolveInfo<'r>) -> BoxFuture<'r, T>
2417            + Send
2418            + Sync
2419            + 'static,
2420    {
2421        let (field, validation) =
2422            object_field_async_with_info::<M, Ctx, T, A, F>(name, resolver, self.registry);
2423        self.push(
2424            field,
2425            T::is_optional(),
2426            std::any::type_name::<T>(),
2427            TypeId::of::<A>(),
2428            validation,
2429        )
2430    }
2431
2432    /// Add an asynchronous field whose resolver returns a `Result`.
2433    pub fn field_result_async<T, A, F>(
2434        &mut self,
2435        name: &'static str,
2436        resolver: F,
2437    ) -> FieldConfig<'_, Ctx>
2438    where
2439        T: OutputType + IntoValue + Send + 'static,
2440        A: InputObject,
2441        F: for<'r> Fn(&'r M, A, &'r Ctx) -> BoxFuture<'r, Result<T, GraphQLError>>
2442            + Send
2443            + Sync
2444            + 'static,
2445    {
2446        self.field_result_async_with_info::<T, A, _>(
2447            name,
2448            move |model: &M, args: A, ctx: &Ctx, _| resolver(model, args, ctx),
2449        )
2450    }
2451
2452    /// Add an asynchronous fallible field whose resolver also receives the [`gql::ResolveInfo`].
2453    pub fn field_result_async_with_info<T, A, F>(
2454        &mut self,
2455        name: &'static str,
2456        resolver: F,
2457    ) -> FieldConfig<'_, Ctx>
2458    where
2459        T: OutputType + IntoValue + Send + 'static,
2460        A: InputObject,
2461        F: for<'r> Fn(
2462                &'r M,
2463                A,
2464                &'r Ctx,
2465                &'r gql::ResolveInfo<'r>,
2466            ) -> BoxFuture<'r, Result<T, GraphQLError>>
2467            + Send
2468            + Sync
2469            + 'static,
2470    {
2471        let (field, validation) =
2472            object_field_result_async_with_info::<M, Ctx, T, A, F>(name, resolver, self.registry);
2473        self.push(
2474            field,
2475            T::is_optional(),
2476            std::any::type_name::<T>(),
2477            TypeId::of::<A>(),
2478            validation,
2479        )
2480    }
2481
2482    /// Add a field whose resolver also receives the executor's [`gql::ResolverContext`].
2483    ///
2484    /// This is the escape hatch for request-level response data: call
2485    /// `execution.context.set_extension("key", value)` from the resolver and the value appears
2486    /// in the response's `extensions` object. Everything the other resolver variants expose is
2487    /// reachable from `execution.info` and `execution.args`.
2488    ///
2489    /// ```
2490    /// # use gurafi::{NoArgs, Object, Schema};
2491    /// # struct Ctx;
2492    /// # #[derive(Object)] struct Giraffe { name: String }
2493    /// # let mut schema = Schema::<Ctx>::new();
2494    /// # schema.object::<Giraffe>(|o| {
2495    /// o.field_with_execution("name", |g: &Giraffe, _: NoArgs, _: &Ctx, execution| {
2496    ///     execution.context.set_extension("servedBy", "gurafi");
2497    ///     g.name.clone()
2498    /// });
2499    /// # });
2500    /// ```
2501    pub fn field_with_execution<T, A, F>(
2502        &mut self,
2503        name: &'static str,
2504        resolver: F,
2505    ) -> FieldConfig<'_, Ctx>
2506    where
2507        T: OutputType + IntoValue + Send + 'static,
2508        A: InputObject,
2509        F: for<'r> Fn(&'r M, A, &'r Ctx, &'r gql::ResolverContext<'r>) -> T + Send + Sync + 'static,
2510    {
2511        let (field, validation) =
2512            object_field_with_execution::<M, Ctx, T, A, F>(name, resolver, self.registry);
2513        self.push(
2514            field,
2515            T::is_optional(),
2516            std::any::type_name::<T>(),
2517            TypeId::of::<A>(),
2518            validation,
2519        )
2520    }
2521
2522    /// Like [`ObjectBuilder::field_with_execution`], but the resolver returns a `Result`.
2523    pub fn field_result_with_execution<T, A, F>(
2524        &mut self,
2525        name: &'static str,
2526        resolver: F,
2527    ) -> FieldConfig<'_, Ctx>
2528    where
2529        T: OutputType + IntoValue + Send + 'static,
2530        A: InputObject,
2531        F: for<'r> Fn(&'r M, A, &'r Ctx, &'r gql::ResolverContext<'r>) -> Result<T, GraphQLError>
2532            + Send
2533            + Sync
2534            + 'static,
2535    {
2536        let (field, validation) =
2537            object_field_result_with_execution::<M, Ctx, T, A, F>(name, resolver, self.registry);
2538        self.push(
2539            field,
2540            T::is_optional(),
2541            std::any::type_name::<T>(),
2542            TypeId::of::<A>(),
2543            validation,
2544        )
2545    }
2546
2547    /// Add a field whose type and arguments come from an implemented interface.
2548    ///
2549    /// Only the resolver is supplied. The schema build looks up the matching interface field
2550    /// (including interfaces that the object implements indirectly), copies its type and
2551    /// arguments, and checks that `A`'s arguments match its declaration. This is the small,
2552    /// resolver-only half of interface inheritance; it does not synthesize a model-backed trait.
2553    ///
2554    /// ```
2555    /// # use gurafi::{ID, NoArgs, Object, Schema};
2556    /// # struct Ctx;
2557    /// #[derive(Object)]
2558    /// struct Giraffe { name: String }
2559    ///
2560    /// let mut schema = Schema::<Ctx>::new();
2561    /// let node = schema.interface("Node", |i| {
2562    ///     i.field::<ID>("id");
2563    /// });
2564    /// schema.object::<Giraffe>(|o| {
2565    ///     o.implements(&node);
2566    ///     o.resolve_inherited("id", |g: &Giraffe, _: NoArgs, _: &Ctx| ID::new(g.name.clone()));
2567    /// });
2568    /// ```
2569    pub fn resolve_inherited<T, A, F>(
2570        &mut self,
2571        name: &'static str,
2572        resolver: F,
2573    ) -> FieldConfig<'_, Ctx>
2574    where
2575        T: OutputType + IntoValue + Send + 'static,
2576        A: InputObject,
2577        F: Fn(&M, A, &Ctx) -> T + Send + Sync + 'static,
2578    {
2579        let expected_args = match A::fields() {
2580            Ok(fields) => fields
2581                .into_iter()
2582                .map(|argument| (argument.name, argument.ty))
2583                .collect(),
2584            Err(error) => {
2585                self.registry.push_error(GraphQLError::new(format!(
2586                    "Arguments for inherited field `{}.{name}` could not be built: {}",
2587                    self.object.name,
2588                    error.message()
2589                )));
2590                Vec::new()
2591            }
2592        };
2593        self.pending_inherited.push(PendingInherited {
2594            object: Arc::clone(&self.object.name),
2595            field: Arc::from(name),
2596            expected_args,
2597        });
2598        self.field(name, resolver)
2599    }
2600
2601    fn push(
2602        &mut self,
2603        field: gql::Field,
2604        rust_nullable: bool,
2605        rust_type_name: &'static str,
2606        args_type: TypeId,
2607        validation: ValidationSlot<Ctx>,
2608    ) -> FieldConfig<'_, Ctx> {
2609        let name = field.name.clone();
2610        let owner = Arc::clone(&self.object.name);
2611        self.object.insert_field(field);
2612        FieldConfig::for_object_checked(
2613            self.registry,
2614            &mut self.object.fields,
2615            self.checks,
2616            owner,
2617            name,
2618            rust_nullable,
2619            rust_type_name,
2620            args_type,
2621            validation,
2622        )
2623    }
2624}
2625
2626impl<Ctx: 'static, M: ObjectModel> std::fmt::Debug for ObjectBuilder<'_, Ctx, M> {
2627    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2628        f.debug_struct("ObjectBuilder")
2629            .field("object", &self.object)
2630            .finish_non_exhaustive()
2631    }
2632}
2633
2634/// Builder for one interface type, received by [`Schema::interface`].
2635pub struct InterfaceBuilder<'a, Ctx: 'static> {
2636    registry: &'a mut TypeRegistry,
2637    interface: gql::InterfaceType,
2638    field_auth: IndexMap<Name, Arc<AuthGuard<Ctx>>>,
2639    auth: Vec<Arc<AuthGuard<Ctx>>>,
2640    auth_error: Option<Arc<str>>,
2641    marker: PhantomData<fn() -> Ctx>,
2642}
2643
2644impl<'a, Ctx: 'static> InterfaceBuilder<'a, Ctx> {
2645    fn new(
2646        existing: Option<gql::InterfaceType>,
2647        field_auth: IndexMap<Name, Arc<AuthGuard<Ctx>>>,
2648        existing_auth_error: Option<Arc<str>>,
2649        registry: &'a mut TypeRegistry,
2650        name: Name,
2651    ) -> Self {
2652        Self {
2653            registry,
2654            interface: existing.unwrap_or_else(|| gql::InterfaceType::new(name)),
2655            field_auth,
2656            auth: Vec::new(),
2657            auth_error: existing_auth_error,
2658            marker: PhantomData,
2659        }
2660    }
2661
2662    fn finish(
2663        self,
2664    ) -> (
2665        gql::InterfaceType,
2666        Vec<Arc<AuthGuard<Ctx>>>,
2667        Option<Arc<str>>,
2668        IndexMap<Name, Arc<AuthGuard<Ctx>>>,
2669    ) {
2670        (self.interface, self.auth, self.auth_error, self.field_auth)
2671    }
2672
2673    /// Set the interface's description.
2674    pub fn description(&mut self, description: impl Into<Arc<str>>) -> &mut Self {
2675        self.interface.description = Some(description.into());
2676        self
2677    }
2678
2679    /// Apply a directive to this interface type.
2680    ///
2681    /// Each call adds an application in declaration order. See [`Schema::directive`] for the
2682    /// definition side and validation rules.
2683    pub fn directive(&mut self, directive: AppliedDirective) -> &mut Self {
2684        self.interface.directives.push(directive);
2685        self
2686    }
2687
2688    /// Whether this interface already declares a field with `name`.
2689    ///
2690    /// Read-only, for extensions that add a field only when it is absent.
2691    #[must_use]
2692    pub fn has_field(&self, name: &str) -> bool {
2693        self.interface
2694            .fields
2695            .keys()
2696            .any(|field| field.as_ref() == name)
2697    }
2698
2699    /// Declare that this interface implements another interface.
2700    ///
2701    /// Both `node` and `&node` are accepted.
2702    pub fn implements(&mut self, interface: impl Into<InterfaceRef>) -> &mut Self {
2703        let interface = interface.into();
2704        let name: Name = Arc::from(interface.name());
2705        if !self
2706            .interface
2707            .interfaces
2708            .iter()
2709            .any(|existing| **existing == *name)
2710        {
2711            self.interface.interfaces.push(name);
2712        }
2713        self
2714    }
2715
2716    /// Require every field of every implementing object to satisfy `predicate`.
2717    ///
2718    /// The rule is inherited by objects that implement this interface, directly or through
2719    /// another interface. It composes with object-level and field-level checks. A rule declared
2720    /// when the interface is reopened adds to the existing rules rather than replacing them.
2721    pub fn auth(&mut self, predicate: impl Fn(&Ctx) -> bool + Send + Sync + 'static) -> &mut Self {
2722        self.auth
2723            .push(crate::field::sync_guard(predicate, self.auth_error.clone()));
2724        self
2725    }
2726
2727    /// Like [`InterfaceBuilder::auth`], but the predicate is asynchronous.
2728    pub fn auth_async(
2729        &mut self,
2730        predicate: impl for<'r> Fn(&'r Ctx) -> BoxFuture<'r, bool> + Send + Sync + 'static,
2731    ) -> &mut Self {
2732        self.auth.push(crate::field::async_guard(
2733            predicate,
2734            self.auth_error.clone(),
2735        ));
2736        self
2737    }
2738
2739    /// Set the message returned when the interface-level authorization denies access.
2740    pub fn auth_error(&mut self, message: impl Into<Arc<str>>) -> &mut Self {
2741        self.auth_error = Some(message.into());
2742        if let Some(auth) = self.auth.last_mut() {
2743            *auth = auth.with_message(self.auth_error.clone());
2744        }
2745        self
2746    }
2747
2748    /// Add a field with no arguments.
2749    ///
2750    /// Interface fields have no resolver: the concrete objects supply one. The field's type must
2751    /// be a covariant match for every implementing object's field. Authorization declared on the
2752    /// field is inherited by those objects.
2753    pub fn field<T: OutputType>(&mut self, name: &'static str) -> InterfaceFieldConfig<'_, Ctx> {
2754        T::register_output(self.registry);
2755        self.interface
2756            .insert_field(gql::Field::new(name, T::output_type()));
2757        InterfaceFieldConfig::new(FieldConfig::for_interface(
2758            self.registry,
2759            &mut self.interface.fields,
2760            &mut self.field_auth,
2761            Arc::from(name),
2762            T::is_optional(),
2763            std::any::type_name::<T>(),
2764        ))
2765    }
2766
2767    /// Add a field whose output type is a runtime-named object.
2768    ///
2769    /// `T` supplies the list and nullability wrappers; `reference` supplies the name. Use it for
2770    /// interface fields that return a dynamically named type such as a connection.
2771    pub fn field_ref<T, N>(
2772        &mut self,
2773        reference: &ObjectRef<N>,
2774        name: &'static str,
2775    ) -> InterfaceFieldConfig<'_, Ctx>
2776    where
2777        T: OutputType,
2778        N: ObjectModel,
2779    {
2780        self.interface
2781            .insert_field(gql::Field::new(name, T::output_type()));
2782        let mut config = FieldConfig::for_interface(
2783            self.registry,
2784            &mut self.interface.fields,
2785            &mut self.field_auth,
2786            Arc::from(name),
2787            T::is_optional(),
2788            std::any::type_name::<T>(),
2789        );
2790        config.as_object_ref(reference);
2791        InterfaceFieldConfig::new(config)
2792    }
2793
2794    /// Add a field with an explicitly built runtime type reference.
2795    pub fn field_ref_type<T: OutputType>(
2796        &mut self,
2797        ty: TypeRef,
2798        name: &'static str,
2799    ) -> InterfaceFieldConfig<'_, Ctx> {
2800        self.interface
2801            .insert_field(gql::Field::new(name, T::output_type()));
2802        let mut config = FieldConfig::for_interface(
2803            self.registry,
2804            &mut self.interface.fields,
2805            &mut self.field_auth,
2806            Arc::from(name),
2807            T::is_optional(),
2808            std::any::type_name::<T>(),
2809        );
2810        config.as_dynamic(ty);
2811        InterfaceFieldConfig::new(config)
2812    }
2813
2814    /// Add a field with arguments.
2815    pub fn field_with<T, A>(&mut self, name: &'static str) -> InterfaceFieldConfig<'_, Ctx>
2816    where
2817        T: OutputType,
2818        A: InputObject,
2819    {
2820        T::register_output(self.registry);
2821        A::register_args(self.registry);
2822        let field = add_arguments::<A>(gql::Field::new(name, T::output_type()), self.registry);
2823        self.interface.insert_field(field);
2824        InterfaceFieldConfig::new(FieldConfig::for_interface(
2825            self.registry,
2826            &mut self.interface.fields,
2827            &mut self.field_auth,
2828            Arc::from(name),
2829            T::is_optional(),
2830            std::any::type_name::<T>(),
2831        ))
2832    }
2833
2834    /// Install a custom abstract type resolver.
2835    ///
2836    /// By default the executor uses each object's `is_type_of` check.
2837    pub fn resolve_type(
2838        &mut self,
2839        resolver: impl Fn(&gql::Value, &gql::ExecutionContext) -> Result<gql::Name, GraphQLError>
2840        + Send
2841        + Sync
2842        + 'static,
2843    ) -> &mut Self {
2844        self.interface.resolve_type = Some(Arc::new(resolver));
2845        self
2846    }
2847}
2848
2849impl<Ctx> std::fmt::Debug for InterfaceBuilder<'_, Ctx> {
2850    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2851        f.debug_struct("InterfaceBuilder")
2852            .field("interface", &self.interface)
2853            .finish_non_exhaustive()
2854    }
2855}
2856
2857/// Builder for one union type, received by [`Schema::union`].
2858pub struct UnionBuilder<'a, Ctx: 'static> {
2859    union: gql::UnionType,
2860    registry: &'a mut TypeRegistry,
2861    marker: PhantomData<fn() -> Ctx>,
2862}
2863
2864impl<'a, Ctx: 'static> UnionBuilder<'a, Ctx> {
2865    fn new(existing: Option<gql::UnionType>, name: Name, registry: &'a mut TypeRegistry) -> Self {
2866        Self {
2867            union: existing.unwrap_or_else(|| gql::UnionType::new(name)),
2868            registry,
2869            marker: PhantomData,
2870        }
2871    }
2872
2873    fn finish(self) -> gql::UnionType {
2874        self.union
2875    }
2876
2877    /// Set the union's description.
2878    pub fn description(&mut self, description: impl Into<Arc<str>>) -> &mut Self {
2879        self.union.description = Some(description.into());
2880        self
2881    }
2882
2883    /// Apply a directive to this union type.
2884    ///
2885    /// Each call adds an application in declaration order. See [`Schema::directive`] for the
2886    /// definition side and validation rules.
2887    pub fn directive(&mut self, directive: AppliedDirective) -> &mut Self {
2888        self.union.directives.push(directive);
2889        self
2890    }
2891
2892    /// Add an object type as a union member.
2893    ///
2894    /// The model is registered as referenced, so a missing `schema.object::<M>(...)` gives the
2895    /// usual "was never registered" build error instead of `gql` failing to find the name.
2896    pub fn member<M: ObjectModel>(&mut self) -> &mut Self {
2897        self.registry.reference_object(M::NAME);
2898        let name: Name = Arc::from(M::NAME);
2899        if !self.union.types.iter().any(|existing| **existing == *name) {
2900            self.union.types.push(name);
2901        }
2902        self
2903    }
2904
2905    /// Add an object created with a runtime name as a union member.
2906    ///
2907    /// This is [`UnionBuilder::member`] for a [`Schema::object_ref`] definition: the reference's
2908    /// dynamic name becomes the member name, and the model still supplies `is_type_of`.
2909    pub fn member_ref<M: ObjectModel>(&mut self, reference: &ObjectRef<M>) -> &mut Self {
2910        self.registry.reference_object(reference.name());
2911        let name: Name = Arc::from(reference.name());
2912        if !self.union.types.iter().any(|existing| **existing == *name) {
2913            self.union.types.push(name);
2914        }
2915        self
2916    }
2917
2918    /// Add an object type by GraphQL name, without a Rust model.
2919    ///
2920    /// The name must match an object registered with [`Schema::object_ref`]; this is the
2921    /// escape hatch for members whose model is not in scope.
2922    pub fn member_name(&mut self, name: impl Into<Name>) -> &mut Self {
2923        let name = name.into();
2924        self.registry.reference_object(Arc::clone(&name));
2925        if !self
2926            .union
2927            .types
2928            .iter()
2929            .any(|existing| existing.as_ref() == name.as_ref())
2930        {
2931            self.union.types.push(name);
2932        }
2933        self
2934    }
2935
2936    /// Install a custom abstract type resolver.
2937    ///
2938    /// By default the executor uses each object's `is_type_of` check.
2939    pub fn resolve_type(
2940        &mut self,
2941        resolver: impl Fn(&gql::Value, &gql::ExecutionContext) -> Result<gql::Name, GraphQLError>
2942        + Send
2943        + Sync
2944        + 'static,
2945    ) -> &mut Self {
2946        self.union.resolve_type = Some(Arc::new(resolver));
2947        self
2948    }
2949}
2950
2951impl<Ctx> std::fmt::Debug for UnionBuilder<'_, Ctx> {
2952    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2953        f.debug_struct("UnionBuilder")
2954            .field("union", &self.union)
2955            .finish_non_exhaustive()
2956    }
2957}
2958
2959/// Builder for query and mutation root fields.
2960pub struct RootBuilder<'a, Ctx: 'static> {
2961    registry: &'a mut TypeRegistry,
2962    fields: &'a mut Vec<gql::Field>,
2963    checks: &'a mut Vec<FieldCheck>,
2964    owner: String,
2965    marker: PhantomData<fn() -> Ctx>,
2966}
2967
2968impl<'a, Ctx: 'static> RootBuilder<'a, Ctx> {
2969    fn new(
2970        registry: &'a mut TypeRegistry,
2971        fields: &'a mut Vec<gql::Field>,
2972        checks: &'a mut Vec<FieldCheck>,
2973        owner: String,
2974    ) -> Self {
2975        Self {
2976            registry,
2977            fields,
2978            checks,
2979            owner,
2980            marker: PhantomData,
2981        }
2982    }
2983
2984    /// Add a synchronous root field whose resolver cannot fail.
2985    pub fn field<T, A, F>(&mut self, name: &'static str, resolver: F) -> FieldConfig<'_, Ctx>
2986    where
2987        T: OutputType + IntoValue + Send + 'static,
2988        A: InputObject,
2989        F: Fn(A, &Ctx) -> T + Send + Sync + 'static,
2990    {
2991        self.field_with_info::<T, A, _>(name, move |args: A, ctx: &Ctx, _| resolver(args, ctx))
2992    }
2993
2994    /// Add a synchronous root field whose output type is a runtime-named object.
2995    ///
2996    /// `reference` supplies the GraphQL name; `T` supplies the list and nullability wrappers.
2997    pub fn field_ref<T, A, F, N>(
2998        &mut self,
2999        reference: &ObjectRef<N>,
3000        name: &'static str,
3001        resolver: F,
3002    ) -> FieldConfig<'_, Ctx>
3003    where
3004        N: ObjectModel,
3005        T: OutputType + IntoValue + Send + 'static,
3006        A: InputObject,
3007        F: Fn(A, &Ctx) -> T + Send + Sync + 'static,
3008    {
3009        let (field, validation) = root_field_with_info::<Ctx, T, A, _>(
3010            name,
3011            move |args: A, ctx: &Ctx, _| resolver(args, ctx),
3012            self.registry,
3013            false,
3014        );
3015        let mut config = self.push(
3016            field,
3017            T::is_optional(),
3018            std::any::type_name::<T>(),
3019            TypeId::of::<A>(),
3020            validation,
3021        );
3022        config.as_object_ref(reference);
3023        config
3024    }
3025
3026    /// Add a synchronous root field with an explicitly built runtime type reference.
3027    pub fn field_ref_type<T, A, F>(
3028        &mut self,
3029        ty: TypeRef,
3030        name: &'static str,
3031        resolver: F,
3032    ) -> FieldConfig<'_, Ctx>
3033    where
3034        T: OutputType + IntoValue + Send + 'static,
3035        A: InputObject,
3036        F: Fn(A, &Ctx) -> T + Send + Sync + 'static,
3037    {
3038        let (field, validation) = root_field_with_info::<Ctx, T, A, _>(
3039            name,
3040            move |args: A, ctx: &Ctx, _| resolver(args, ctx),
3041            self.registry,
3042            false,
3043        );
3044        let mut config = self.push(
3045            field,
3046            T::is_optional(),
3047            std::any::type_name::<T>(),
3048            TypeId::of::<A>(),
3049            validation,
3050        );
3051        config.as_dynamic(ty);
3052        config
3053    }
3054
3055    /// Add a synchronous root field whose resolver also receives the [`gql::ResolveInfo`].
3056    pub fn field_with_info<T, A, F>(
3057        &mut self,
3058        name: &'static str,
3059        resolver: F,
3060    ) -> FieldConfig<'_, Ctx>
3061    where
3062        T: OutputType + IntoValue + Send + 'static,
3063        A: InputObject,
3064        F: for<'r> Fn(A, &'r Ctx, &'r gql::ResolveInfo<'r>) -> T + Send + Sync + 'static,
3065    {
3066        let (field, validation) =
3067            root_field_with_info::<Ctx, T, A, F>(name, resolver, self.registry, true);
3068        self.push(
3069            field,
3070            T::is_optional(),
3071            std::any::type_name::<T>(),
3072            TypeId::of::<A>(),
3073            validation,
3074        )
3075    }
3076
3077    /// Add a synchronous root field whose resolver returns a `Result`.
3078    pub fn field_result<T, A, F>(&mut self, name: &'static str, resolver: F) -> FieldConfig<'_, Ctx>
3079    where
3080        T: OutputType + IntoValue + Send + 'static,
3081        A: InputObject,
3082        F: Fn(A, &Ctx) -> Result<T, GraphQLError> + Send + Sync + 'static,
3083    {
3084        self.field_result_with_info::<T, A, _>(name, move |args: A, ctx: &Ctx, _| {
3085            resolver(args, ctx)
3086        })
3087    }
3088
3089    /// Add a synchronous fallible root field whose resolver also receives the [`gql::ResolveInfo`].
3090    pub fn field_result_with_info<T, A, F>(
3091        &mut self,
3092        name: &'static str,
3093        resolver: F,
3094    ) -> FieldConfig<'_, Ctx>
3095    where
3096        T: OutputType + IntoValue + Send + 'static,
3097        A: InputObject,
3098        F: for<'r> Fn(A, &'r Ctx, &'r gql::ResolveInfo<'r>) -> Result<T, GraphQLError>
3099            + Send
3100            + Sync
3101            + 'static,
3102    {
3103        let (field, validation) =
3104            root_field_result_with_info::<Ctx, T, A, F>(name, resolver, self.registry);
3105        self.push(
3106            field,
3107            T::is_optional(),
3108            std::any::type_name::<T>(),
3109            TypeId::of::<A>(),
3110            validation,
3111        )
3112    }
3113
3114    /// Add a synchronous root field whose resolver returns a typed `Result`.
3115    ///
3116    /// The field's type is a generated `<Parent><Field>Result` union, as described on
3117    /// [`ObjectBuilder::field_result_union`]. The parent name is the configured query, mutation
3118    /// or subscription root name.
3119    pub fn field_result_union<T, E, A, F>(
3120        &mut self,
3121        name: &'static str,
3122        resolver: F,
3123    ) -> FieldConfig<'_, Ctx>
3124    where
3125        T: OutputType + IntoValue + Send + 'static,
3126        E: ErrorUnionModel,
3127        A: InputObject,
3128        F: Fn(A, &Ctx) -> core::result::Result<T, E> + Send + Sync + 'static,
3129    {
3130        self.field_result_union_with_info::<T, E, A, _>(name, move |args: A, ctx: &Ctx, _| {
3131            resolver(args, ctx)
3132        })
3133    }
3134
3135    /// Add a synchronous typed-result root field whose resolver also receives
3136    /// [`gql::ResolveInfo`].
3137    pub fn field_result_union_with_info<T, E, A, F>(
3138        &mut self,
3139        name: &'static str,
3140        resolver: F,
3141    ) -> FieldConfig<'_, Ctx>
3142    where
3143        T: OutputType + IntoValue + Send + 'static,
3144        E: ErrorUnionModel,
3145        A: InputObject,
3146        F: for<'r> Fn(A, &'r Ctx, &'r gql::ResolveInfo<'r>) -> core::result::Result<T, E>
3147            + Send
3148            + Sync
3149            + 'static,
3150    {
3151        let (field, validation) = root_field_result_union_with_info::<Ctx, T, E, A, F>(
3152            name,
3153            resolver,
3154            self.registry,
3155            &self.owner,
3156        );
3157        self.push(
3158            field,
3159            false,
3160            std::any::type_name::<T>(),
3161            TypeId::of::<A>(),
3162            validation,
3163        )
3164    }
3165
3166    /// Add an asynchronous typed-result root field.
3167    pub fn field_result_union_async<T, E, A, F>(
3168        &mut self,
3169        name: &'static str,
3170        resolver: F,
3171    ) -> FieldConfig<'_, Ctx>
3172    where
3173        T: OutputType + IntoValue + Send + 'static,
3174        E: ErrorUnionModel,
3175        A: InputObject,
3176        F: for<'r> Fn(A, &'r Ctx) -> BoxFuture<'r, core::result::Result<T, E>>
3177            + Send
3178            + Sync
3179            + 'static,
3180    {
3181        self.field_result_union_async_with_info::<T, E, A, _>(name, move |args: A, ctx: &Ctx, _| {
3182            resolver(args, ctx)
3183        })
3184    }
3185
3186    /// Add an asynchronous typed-result root field whose resolver also receives
3187    /// [`gql::ResolveInfo`].
3188    pub fn field_result_union_async_with_info<T, E, A, F>(
3189        &mut self,
3190        name: &'static str,
3191        resolver: F,
3192    ) -> FieldConfig<'_, Ctx>
3193    where
3194        T: OutputType + IntoValue + Send + 'static,
3195        E: ErrorUnionModel,
3196        A: InputObject,
3197        F: for<'r> Fn(
3198                A,
3199                &'r Ctx,
3200                &'r gql::ResolveInfo<'r>,
3201            ) -> BoxFuture<'r, core::result::Result<T, E>>
3202            + Send
3203            + Sync
3204            + 'static,
3205    {
3206        let (field, validation) = root_field_result_union_async_with_info::<Ctx, T, E, A, F>(
3207            name,
3208            resolver,
3209            self.registry,
3210            &self.owner,
3211        );
3212        self.push(
3213            field,
3214            false,
3215            std::any::type_name::<T>(),
3216            TypeId::of::<A>(),
3217            validation,
3218        )
3219    }
3220
3221    /// Add an asynchronous root field whose resolver cannot fail.
3222    pub fn field_async<T, A, F>(&mut self, name: &'static str, resolver: F) -> FieldConfig<'_, Ctx>
3223    where
3224        T: OutputType + IntoValue + Send + 'static,
3225        A: InputObject,
3226        F: for<'r> Fn(A, &'r Ctx) -> BoxFuture<'r, T> + Send + Sync + 'static,
3227    {
3228        self.field_async_with_info::<T, A, _>(name, move |args: A, ctx: &Ctx, _| {
3229            resolver(args, ctx)
3230        })
3231    }
3232
3233    /// Add an asynchronous root field whose resolver also receives the [`gql::ResolveInfo`].
3234    pub fn field_async_with_info<T, A, F>(
3235        &mut self,
3236        name: &'static str,
3237        resolver: F,
3238    ) -> FieldConfig<'_, Ctx>
3239    where
3240        T: OutputType + IntoValue + Send + 'static,
3241        A: InputObject,
3242        F: for<'r> Fn(A, &'r Ctx, &'r gql::ResolveInfo<'r>) -> BoxFuture<'r, T>
3243            + Send
3244            + Sync
3245            + 'static,
3246    {
3247        let (field, validation) =
3248            root_field_async_with_info::<Ctx, T, A, F>(name, resolver, self.registry);
3249        self.push(
3250            field,
3251            T::is_optional(),
3252            std::any::type_name::<T>(),
3253            TypeId::of::<A>(),
3254            validation,
3255        )
3256    }
3257
3258    /// Add an asynchronous root field whose resolver returns a `Result`.
3259    pub fn field_result_async<T, A, F>(
3260        &mut self,
3261        name: &'static str,
3262        resolver: F,
3263    ) -> FieldConfig<'_, Ctx>
3264    where
3265        T: OutputType + IntoValue + Send + 'static,
3266        A: InputObject,
3267        F: for<'r> Fn(A, &'r Ctx) -> BoxFuture<'r, Result<T, GraphQLError>> + Send + Sync + 'static,
3268    {
3269        self.field_result_async_with_info::<T, A, _>(name, move |args: A, ctx: &Ctx, _| {
3270            resolver(args, ctx)
3271        })
3272    }
3273
3274    /// Add an asynchronous fallible root field whose resolver also receives the
3275    /// [`gql::ResolveInfo`].
3276    pub fn field_result_async_with_info<T, A, F>(
3277        &mut self,
3278        name: &'static str,
3279        resolver: F,
3280    ) -> FieldConfig<'_, Ctx>
3281    where
3282        T: OutputType + IntoValue + Send + 'static,
3283        A: InputObject,
3284        F: for<'r> Fn(
3285                A,
3286                &'r Ctx,
3287                &'r gql::ResolveInfo<'r>,
3288            ) -> BoxFuture<'r, Result<T, GraphQLError>>
3289            + Send
3290            + Sync
3291            + 'static,
3292    {
3293        let (field, validation) =
3294            root_field_result_async_with_info::<Ctx, T, A, F>(name, resolver, self.registry);
3295        self.push(
3296            field,
3297            T::is_optional(),
3298            std::any::type_name::<T>(),
3299            TypeId::of::<A>(),
3300            validation,
3301        )
3302    }
3303
3304    /// Add a root field whose resolver also receives the executor's [`gql::ResolverContext`].
3305    ///
3306    /// Use it to set response extensions with `execution.context.set_extension("key", value)`.
3307    pub fn field_with_execution<T, A, F>(
3308        &mut self,
3309        name: &'static str,
3310        resolver: F,
3311    ) -> FieldConfig<'_, Ctx>
3312    where
3313        T: OutputType + IntoValue + Send + 'static,
3314        A: InputObject,
3315        F: for<'r> Fn(A, &'r Ctx, &'r gql::ResolverContext<'r>) -> T + Send + Sync + 'static,
3316    {
3317        let (field, validation) =
3318            root_field_with_execution::<Ctx, T, A, F>(name, resolver, self.registry);
3319        self.push(
3320            field,
3321            T::is_optional(),
3322            std::any::type_name::<T>(),
3323            TypeId::of::<A>(),
3324            validation,
3325        )
3326    }
3327
3328    /// Like [`RootBuilder::field_with_execution`], but the resolver returns a `Result`.
3329    pub fn field_result_with_execution<T, A, F>(
3330        &mut self,
3331        name: &'static str,
3332        resolver: F,
3333    ) -> FieldConfig<'_, Ctx>
3334    where
3335        T: OutputType + IntoValue + Send + 'static,
3336        A: InputObject,
3337        F: for<'r> Fn(A, &'r Ctx, &'r gql::ResolverContext<'r>) -> Result<T, GraphQLError>
3338            + Send
3339            + Sync
3340            + 'static,
3341    {
3342        let (field, validation) =
3343            root_field_result_with_execution::<Ctx, T, A, F>(name, resolver, self.registry);
3344        self.push(
3345            field,
3346            T::is_optional(),
3347            std::any::type_name::<T>(),
3348            TypeId::of::<A>(),
3349            validation,
3350        )
3351    }
3352
3353    fn push(
3354        &mut self,
3355        field: gql::Field,
3356        rust_nullable: bool,
3357        rust_type_name: &'static str,
3358        args_type: TypeId,
3359        validation: ValidationSlot<Ctx>,
3360    ) -> FieldConfig<'_, Ctx> {
3361        let name = field.name.clone();
3362        self.fields.push(field);
3363        FieldConfig::for_fields_checked(
3364            self.registry,
3365            self.fields,
3366            self.checks,
3367            self.owner.clone(),
3368            name,
3369            rust_nullable,
3370            rust_type_name,
3371            args_type,
3372            validation,
3373        )
3374    }
3375}
3376
3377impl<Ctx> std::fmt::Debug for RootBuilder<'_, Ctx> {
3378    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3379        f.debug_struct("RootBuilder")
3380            .field("fields", &self.fields.len())
3381            .finish_non_exhaustive()
3382    }
3383}
3384
3385/// Builder for subscription root fields.
3386///
3387/// A subscription field's `subscribe` resolver returns a stream of events. The executor treats
3388/// each event as the root value of the subscription field and runs the field's `resolve`
3389/// resolver to extract the value of the field. `gurafi` uses that to keep the simple API:
3390/// [`SubscriptionBuilder::field`] takes a stream of the field's values and arranges the root
3391/// object and the extracting resolver for you.
3392///
3393/// Use [`SubscriptionBuilder::field_map`] when the event type differs from the field's type.
3394pub struct SubscriptionBuilder<'a, Ctx: 'static> {
3395    registry: &'a mut TypeRegistry,
3396    fields: &'a mut Vec<gql::Field>,
3397    checks: &'a mut Vec<FieldCheck>,
3398    owner: String,
3399    marker: PhantomData<fn() -> Ctx>,
3400}
3401
3402impl<'a, Ctx: 'static> SubscriptionBuilder<'a, Ctx> {
3403    fn new(
3404        registry: &'a mut TypeRegistry,
3405        fields: &'a mut Vec<gql::Field>,
3406        checks: &'a mut Vec<FieldCheck>,
3407        owner: String,
3408    ) -> Self {
3409        Self {
3410            registry,
3411            fields,
3412            checks,
3413            owner,
3414            marker: PhantomData,
3415        }
3416    }
3417
3418    /// Add a subscription field.
3419    ///
3420    /// `subscribe` is called once per subscription to create the event stream. Each item is the
3421    /// field's own value (or an error), not a root object: `gurafi` wraps it and extracts it
3422    /// again when the executor resolves the field, so the common case stays simple. The stream
3423    /// must be `Send + 'static`, so anything it borrows from the context must be cloned first
3424    /// (channels and `Arc`s are the usual choice).
3425    pub fn field<A, T, F, S>(&mut self, name: &'static str, subscribe: F) -> FieldConfig<'_, Ctx>
3426    where
3427        A: InputObject,
3428        T: OutputType + IntoValue + Send + 'static,
3429        S: Stream<Item = Result<T, GraphQLError>> + Send + 'static,
3430        F: Fn(A, &Ctx) -> S + Send + Sync + 'static,
3431    {
3432        self.field_with_info::<A, T, _, S>(name, move |args: A, ctx: &Ctx, _| subscribe(args, ctx))
3433    }
3434
3435    /// Add a subscription field whose output type is a runtime-named object.
3436    ///
3437    /// The stream yields the object's model; `reference` supplies the GraphQL name and `T`
3438    /// supplies the list and nullability wrappers.
3439    pub fn field_ref<A, T, F, S, N>(
3440        &mut self,
3441        reference: &ObjectRef<N>,
3442        name: &'static str,
3443        subscribe: F,
3444    ) -> FieldConfig<'_, Ctx>
3445    where
3446        A: InputObject,
3447        N: ObjectModel,
3448        T: OutputType + IntoValue + Send + 'static,
3449        S: Stream<Item = Result<T, GraphQLError>> + Send + 'static,
3450        F: Fn(A, &Ctx) -> S + Send + Sync + 'static,
3451    {
3452        let (field, validation) = subscription_field::<Ctx, A, T, _, S>(
3453            name,
3454            move |args: A, ctx: &Ctx, _| subscribe(args, ctx),
3455            self.registry,
3456            false,
3457        );
3458        let mut config = self.push(
3459            field,
3460            T::is_optional(),
3461            std::any::type_name::<T>(),
3462            TypeId::of::<A>(),
3463            validation,
3464        );
3465        config.as_object_ref(reference);
3466        config
3467    }
3468
3469    /// Add a subscription field with an explicitly built runtime type reference.
3470    pub fn field_ref_type<A, T, F, S>(
3471        &mut self,
3472        ty: TypeRef,
3473        name: &'static str,
3474        subscribe: F,
3475    ) -> FieldConfig<'_, Ctx>
3476    where
3477        A: InputObject,
3478        T: OutputType + IntoValue + Send + 'static,
3479        S: Stream<Item = Result<T, GraphQLError>> + Send + 'static,
3480        F: Fn(A, &Ctx) -> S + Send + Sync + 'static,
3481    {
3482        let (field, validation) = subscription_field::<Ctx, A, T, _, S>(
3483            name,
3484            move |args: A, ctx: &Ctx, _| subscribe(args, ctx),
3485            self.registry,
3486            false,
3487        );
3488        let mut config = self.push(
3489            field,
3490            T::is_optional(),
3491            std::any::type_name::<T>(),
3492            TypeId::of::<A>(),
3493            validation,
3494        );
3495        config.as_dynamic(ty);
3496        config
3497    }
3498
3499    /// Add a subscription field whose `subscribe` also receives the [`gql::ResolveInfo`].
3500    pub fn field_with_info<A, T, F, S>(
3501        &mut self,
3502        name: &'static str,
3503        subscribe: F,
3504    ) -> FieldConfig<'_, Ctx>
3505    where
3506        A: InputObject,
3507        T: OutputType + IntoValue + Send + 'static,
3508        S: Stream<Item = Result<T, GraphQLError>> + Send + 'static,
3509        F: for<'r> Fn(A, &'r Ctx, &'r gql::ResolveInfo<'r>) -> S + Send + Sync + 'static,
3510    {
3511        let (field, validation) =
3512            subscription_field::<Ctx, A, T, F, S>(name, subscribe, self.registry, true);
3513        self.push(
3514            field,
3515            T::is_optional(),
3516            std::any::type_name::<T>(),
3517            TypeId::of::<A>(),
3518            validation,
3519        )
3520    }
3521
3522    /// Add a subscription whose events are typed results.
3523    ///
3524    /// Each stream item is either `Ok(T)` (the generated success payload with `data: T`) or
3525    /// `Err(E)` (the matching error payload object), exactly like
3526    /// [`ObjectBuilder::field_result_union`]. The field type is the generated result union, so
3527    /// a client can select error payload fields from an event.
3528    pub fn field_result_union<T, E, A, F, S>(
3529        &mut self,
3530        name: &'static str,
3531        subscribe: F,
3532    ) -> FieldConfig<'_, Ctx>
3533    where
3534        A: InputObject,
3535        T: OutputType + IntoValue + Send + 'static,
3536        E: ErrorUnionModel,
3537        S: Stream<Item = core::result::Result<T, E>> + Send + 'static,
3538        F: Fn(A, &Ctx) -> S + Send + Sync + 'static,
3539    {
3540        self.field_result_union_with_info::<T, E, A, _, S>(name, move |args: A, ctx: &Ctx, _| {
3541            subscribe(args, ctx)
3542        })
3543    }
3544
3545    /// Add a typed-result subscription whose `subscribe` also receives [`gql::ResolveInfo`].
3546    pub fn field_result_union_with_info<T, E, A, F, S>(
3547        &mut self,
3548        name: &'static str,
3549        subscribe: F,
3550    ) -> FieldConfig<'_, Ctx>
3551    where
3552        A: InputObject,
3553        T: OutputType + IntoValue + Send + 'static,
3554        E: ErrorUnionModel,
3555        S: Stream<Item = core::result::Result<T, E>> + Send + 'static,
3556        F: for<'r> Fn(A, &'r Ctx, &'r gql::ResolveInfo<'r>) -> S + Send + Sync + 'static,
3557    {
3558        let (field, validation) = subscription_field_result_union::<Ctx, T, E, A, F, S>(
3559            name,
3560            subscribe,
3561            self.registry,
3562            &self.owner,
3563        );
3564        self.push(
3565            field,
3566            false,
3567            std::any::type_name::<T>(),
3568            TypeId::of::<A>(),
3569            validation,
3570        )
3571    }
3572
3573    /// Add a subscription whose events are mapped to the field value by a resolver.
3574    ///
3575    /// This is the Pothos-style form: the stream produces an event `E`, and `resolve` turns each
3576    /// event into the field's value `T`. Use it when the event carries more than the field's
3577    /// own value (an envelope with metadata, or several correlated updates).
3578    ///
3579    /// ```
3580    /// use futures::stream;
3581    /// use gurafi::{NoArgs, Schema};
3582    ///
3583    /// struct Ctx;
3584    ///
3585    /// #[derive(Clone)]
3586    /// struct BornEvent {
3587    ///     name: String,
3588    /// }
3589    ///
3590    /// let mut schema = Schema::<Ctx>::new();
3591    /// schema.query(|q| {
3592    ///     q.field("ok", |_: NoArgs, _: &Ctx| true);
3593    /// });
3594    /// schema.subscription(|s| {
3595    ///     s.field_map::<NoArgs, BornEvent, String, _, _, _>(
3596    ///         "giraffeBorn",
3597    ///         |_: NoArgs, _: &Ctx| {
3598    ///             stream::iter(vec![Ok(BornEvent {
3599    ///                 name: "Melman".into(),
3600    ///             })])
3601    ///         },
3602    ///         |event: &BornEvent, _: NoArgs, _: &Ctx| Ok(event.name.clone()),
3603    ///     );
3604    /// });
3605    /// let schema = schema.build().expect("schema builds");
3606    /// # let _ = schema;
3607    /// ```
3608    pub fn field_map<A, E, T, F, S, R>(
3609        &mut self,
3610        name: &'static str,
3611        subscribe: F,
3612        resolve: R,
3613    ) -> FieldConfig<'_, Ctx>
3614    where
3615        A: InputObject,
3616        E: Send + Sync + 'static,
3617        T: OutputType + IntoValue + Send + 'static,
3618        S: Stream<Item = Result<E, GraphQLError>> + Send + 'static,
3619        F: Fn(A, &Ctx) -> S + Send + Sync + 'static,
3620        R: for<'r> Fn(&'r E, A, &'r Ctx) -> Result<T, GraphQLError> + Send + Sync + 'static,
3621    {
3622        T::register_output(self.registry);
3623        A::register_args(self.registry);
3624        let validation = ValidationSlot::new();
3625        let resolve_validation = validation.clone();
3626        let subscribe = Arc::new(subscribe);
3627        let resolve = Arc::new(resolve);
3628        let field = add_arguments::<A>(gql::Field::new(name, T::output_type()), self.registry)
3629            .resolve(move |context| {
3630                let resolve = Arc::clone(&resolve);
3631                let validation = resolve_validation.clone();
3632                Box::pin(async move {
3633                    let event = context.parent.as_external::<E>().ok_or_else(|| {
3634                        GraphQLError::new(format!(
3635                            "Subscription event for \"{}\" had an unexpected type.",
3636                            context.info.field_name
3637                        ))
3638                    })?;
3639                    // The subscription already validated the input once. Per-event resolution
3640                    // converts the same coerced arguments without re-running input-level
3641                    // validation, then runs the field validator exactly once per event.
3642                    let args = coerce_args_without_validation::<A>(
3643                        context.args,
3644                        context.info.parent_type,
3645                        context.info.field_name,
3646                    )?;
3647                    let ctx = context.context.require_data::<Ctx>()?;
3648                    validation.run(&args, ctx)?;
3649                    match resolve(event, args, ctx) {
3650                        Ok(value) => value.into_value(),
3651                        Err(error) => Err(error),
3652                    }
3653                })
3654            })
3655            .subscribe(move |context| {
3656                let subscribe = Arc::clone(&subscribe);
3657                Box::pin(async move {
3658                    let args = coerce_args::<A>(
3659                        context.args,
3660                        context.info.parent_type,
3661                        context.info.field_name,
3662                    )?;
3663                    let ctx = context.context.require_data::<Ctx>()?;
3664                    let stream = subscribe(args, ctx);
3665                    let mapped = stream.map(|item| match item {
3666                        Ok(event) => Ok(gql::Value::external(event)),
3667                        Err(error) => Err(error),
3668                    });
3669                    Ok(Box::pin(mapped) as gql::SubscriptionStream)
3670                })
3671            });
3672        self.push(
3673            field,
3674            T::is_optional(),
3675            std::any::type_name::<T>(),
3676            TypeId::of::<A>(),
3677            validation,
3678        )
3679    }
3680
3681    fn push(
3682        &mut self,
3683        field: gql::Field,
3684        rust_nullable: bool,
3685        rust_type_name: &'static str,
3686        args_type: TypeId,
3687        validation: ValidationSlot<Ctx>,
3688    ) -> FieldConfig<'_, Ctx> {
3689        let name = field.name.clone();
3690        self.fields.push(field);
3691        FieldConfig::for_fields_checked(
3692            self.registry,
3693            self.fields,
3694            self.checks,
3695            self.owner.clone(),
3696            name,
3697            rust_nullable,
3698            rust_type_name,
3699            args_type,
3700            validation,
3701        )
3702    }
3703}
3704
3705impl<Ctx> std::fmt::Debug for SubscriptionBuilder<'_, Ctx> {
3706    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3707        f.debug_struct("SubscriptionBuilder")
3708            .field("fields", &self.fields.len())
3709            .finish_non_exhaustive()
3710    }
3711}
3712
3713fn add_arguments<A: InputObject>(mut field: gql::Field, registry: &mut TypeRegistry) -> gql::Field {
3714    if A::one_of() {
3715        registry.push_error(GraphQLError::new(format!(
3716            "`{}` is a `@oneOf` input and cannot be used directly as field `{}`'s arguments. Wrap \
3717             it in an arguments type so it stays one argument: `struct Args {{ by: {} }}`.",
3718            std::any::type_name::<A>(),
3719            field.name,
3720            std::any::type_name::<A>(),
3721        )));
3722    }
3723    match A::fields() {
3724        Ok(arguments) => {
3725            for argument in arguments {
3726                field = field.arg(argument);
3727            }
3728        }
3729        Err(error) => registry.push_error(GraphQLError::new(format!(
3730            "Arguments for field `{}` could not be built: {}",
3731            field.name,
3732            error.message()
3733        ))),
3734    }
3735    field
3736}
3737
3738fn object_field<M, Ctx, T, A, F>(
3739    name: &'static str,
3740    resolver: F,
3741    registry: &mut TypeRegistry,
3742) -> (gql::Field, ValidationSlot<Ctx>)
3743where
3744    M: ObjectModel,
3745    Ctx: 'static,
3746    T: OutputType + IntoValue + Send + 'static,
3747    A: InputObject,
3748    F: Fn(&M, A, &Ctx) -> T + Send + Sync + 'static,
3749{
3750    object_field_with_info::<M, Ctx, T, A, _>(
3751        name,
3752        move |model: &M, args: A, ctx: &Ctx, _| resolver(model, args, ctx),
3753        registry,
3754        true,
3755    )
3756}
3757
3758fn object_field_with_info<M, Ctx, T, A, F>(
3759    name: &'static str,
3760    resolver: F,
3761    registry: &mut TypeRegistry,
3762    register_output: bool,
3763) -> (gql::Field, ValidationSlot<Ctx>)
3764where
3765    M: ObjectModel,
3766    Ctx: 'static,
3767    T: OutputType + IntoValue + Send + 'static,
3768    A: InputObject,
3769    F: for<'r> Fn(&'r M, A, &'r Ctx, &'r gql::ResolveInfo<'r>) -> T + Send + Sync + 'static,
3770{
3771    if register_output {
3772        T::register_output(registry);
3773    }
3774    A::register_args(registry);
3775    let resolver = Arc::new(resolver);
3776    let validation = ValidationSlot::new();
3777    let hook = validation.clone();
3778    let field = add_arguments::<A>(gql::Field::new(name, T::output_type()), registry).resolve(
3779        move |context| {
3780            let resolver = Arc::clone(&resolver);
3781            let hook = hook.clone();
3782            Box::pin(async move {
3783                let model = model_ref::<M>(
3784                    context.parent,
3785                    context.info.parent_type,
3786                    context.info.field_name,
3787                )?;
3788                let args = coerce_args::<A>(
3789                    context.args,
3790                    context.info.parent_type,
3791                    context.info.field_name,
3792                )?;
3793                let ctx = context.context.require_data::<Ctx>()?;
3794                hook.run(&args, ctx)?;
3795                (resolver)(model, args, ctx, context.info).into_value()
3796            })
3797        },
3798    );
3799    (field, validation)
3800}
3801
3802fn object_field_result_with_info<M, Ctx, T, A, F>(
3803    name: &'static str,
3804    resolver: F,
3805    registry: &mut TypeRegistry,
3806) -> (gql::Field, ValidationSlot<Ctx>)
3807where
3808    M: ObjectModel,
3809    Ctx: 'static,
3810    T: OutputType + IntoValue + Send + 'static,
3811    A: InputObject,
3812    F: for<'r> Fn(&'r M, A, &'r Ctx, &'r gql::ResolveInfo<'r>) -> Result<T, GraphQLError>
3813        + Send
3814        + Sync
3815        + 'static,
3816{
3817    T::register_output(registry);
3818    A::register_args(registry);
3819    let resolver = Arc::new(resolver);
3820    let validation = ValidationSlot::new();
3821    let hook = validation.clone();
3822    let field = add_arguments::<A>(gql::Field::new(name, T::output_type()), registry).resolve(
3823        move |context| {
3824            let resolver = Arc::clone(&resolver);
3825            let hook = hook.clone();
3826            Box::pin(async move {
3827                let model = model_ref::<M>(
3828                    context.parent,
3829                    context.info.parent_type,
3830                    context.info.field_name,
3831                )?;
3832                let args = coerce_args::<A>(
3833                    context.args,
3834                    context.info.parent_type,
3835                    context.info.field_name,
3836                )?;
3837                let ctx = context.context.require_data::<Ctx>()?;
3838                hook.run(&args, ctx)?;
3839                match (resolver)(model, args, ctx, context.info) {
3840                    Ok(value) => value.into_value(),
3841                    Err(error) => Err(error),
3842                }
3843            })
3844        },
3845    );
3846    (field, validation)
3847}
3848
3849fn object_field_result_union_with_info<M, Ctx, T, E, A, F>(
3850    name: &'static str,
3851    resolver: F,
3852    registry: &mut TypeRegistry,
3853    parent: &str,
3854) -> (gql::Field, ValidationSlot<Ctx>)
3855where
3856    M: ObjectModel,
3857    Ctx: 'static,
3858    T: OutputType + IntoValue + Send + 'static,
3859    E: ErrorUnionModel,
3860    A: InputObject,
3861    F: for<'r> Fn(&'r M, A, &'r Ctx, &'r gql::ResolveInfo<'r>) -> core::result::Result<T, E>
3862        + Send
3863        + Sync
3864        + 'static,
3865{
3866    let ty = result_union_type_ref::<T, E>(registry, parent, name);
3867    A::register_args(registry);
3868    let resolver = Arc::new(resolver);
3869    let validation = ValidationSlot::new();
3870    let hook = validation.clone();
3871    let field = add_arguments::<A>(gql::Field::new(name, ty), registry).resolve(move |context| {
3872        let resolver = Arc::clone(&resolver);
3873        let hook = hook.clone();
3874        Box::pin(async move {
3875            let model = model_ref::<M>(
3876                context.parent,
3877                context.info.parent_type,
3878                context.info.field_name,
3879            )?;
3880            let args = coerce_args::<A>(
3881                context.args,
3882                context.info.parent_type,
3883                context.info.field_name,
3884            )?;
3885            let ctx = context.context.require_data::<Ctx>()?;
3886            hook.run(&args, ctx)?;
3887            let result = match (resolver)(model, args, ctx, context.info) {
3888                Ok(value) => value
3889                    .into_value()
3890                    .map(|data| gql::Value::external(ResultSuccess::new(data))),
3891                Err(error) => error.into_value(),
3892            };
3893            #[cfg(feature = "tracing")]
3894            if tracing::enabled!(target: "gurafi::error_union", tracing::Level::TRACE) {
3895                tracing::trace!(
3896                    target: "gurafi::error_union",
3897                    field = name,
3898                    outcome = if result.is_ok() { "success" } else { "error" },
3899                    "gurafi.error_union.dispatch"
3900                );
3901            }
3902            result
3903        })
3904    });
3905    (field, validation)
3906}
3907
3908fn object_field_result_union_async_with_info<M, Ctx, T, E, A, F>(
3909    name: &'static str,
3910    resolver: F,
3911    registry: &mut TypeRegistry,
3912    parent: &str,
3913) -> (gql::Field, ValidationSlot<Ctx>)
3914where
3915    M: ObjectModel,
3916    Ctx: 'static,
3917    T: OutputType + IntoValue + Send + 'static,
3918    E: ErrorUnionModel,
3919    A: InputObject,
3920    F: for<'r> Fn(
3921            &'r M,
3922            A,
3923            &'r Ctx,
3924            &'r gql::ResolveInfo<'r>,
3925        ) -> BoxFuture<'r, core::result::Result<T, E>>
3926        + Send
3927        + Sync
3928        + 'static,
3929{
3930    let ty = result_union_type_ref::<T, E>(registry, parent, name);
3931    A::register_args(registry);
3932    let resolver = Arc::new(resolver);
3933    let validation = ValidationSlot::new();
3934    let hook = validation.clone();
3935    let field = add_arguments::<A>(gql::Field::new(name, ty), registry).resolve(move |context| {
3936        let resolver = Arc::clone(&resolver);
3937        let hook = hook.clone();
3938        Box::pin(async move {
3939            let model = model_ref::<M>(
3940                context.parent,
3941                context.info.parent_type,
3942                context.info.field_name,
3943            )?;
3944            let args = coerce_args::<A>(
3945                context.args,
3946                context.info.parent_type,
3947                context.info.field_name,
3948            )?;
3949            let ctx = context.context.require_data::<Ctx>()?;
3950            hook.run(&args, ctx)?;
3951            let result = match (resolver)(model, args, ctx, context.info).await {
3952                Ok(value) => value
3953                    .into_value()
3954                    .map(|data| gql::Value::external(ResultSuccess::new(data))),
3955                Err(error) => error.into_value(),
3956            };
3957            #[cfg(feature = "tracing")]
3958            if tracing::enabled!(target: "gurafi::error_union", tracing::Level::TRACE) {
3959                tracing::trace!(
3960                    target: "gurafi::error_union",
3961                    field = name,
3962                    outcome = if result.is_ok() { "success" } else { "error" },
3963                    "gurafi.error_union.dispatch"
3964                );
3965            }
3966            result
3967        })
3968    });
3969    (field, validation)
3970}
3971
3972fn object_field_async_with_info<M, Ctx, T, A, F>(
3973    name: &'static str,
3974    resolver: F,
3975    registry: &mut TypeRegistry,
3976) -> (gql::Field, ValidationSlot<Ctx>)
3977where
3978    M: ObjectModel,
3979    Ctx: 'static,
3980    T: OutputType + IntoValue + Send + 'static,
3981    A: InputObject,
3982    F: for<'r> Fn(&'r M, A, &'r Ctx, &'r gql::ResolveInfo<'r>) -> BoxFuture<'r, T>
3983        + Send
3984        + Sync
3985        + 'static,
3986{
3987    T::register_output(registry);
3988    A::register_args(registry);
3989    let resolver = Arc::new(resolver);
3990    let validation = ValidationSlot::new();
3991    let hook = validation.clone();
3992    let field = add_arguments::<A>(gql::Field::new(name, T::output_type()), registry).resolve(
3993        move |context| {
3994            let resolver = Arc::clone(&resolver);
3995            let hook = hook.clone();
3996            Box::pin(async move {
3997                let model = model_ref::<M>(
3998                    context.parent,
3999                    context.info.parent_type,
4000                    context.info.field_name,
4001                )?;
4002                let args = coerce_args::<A>(
4003                    context.args,
4004                    context.info.parent_type,
4005                    context.info.field_name,
4006                )?;
4007                let ctx = context.context.require_data::<Ctx>()?;
4008                hook.run(&args, ctx)?;
4009                (resolver)(model, args, ctx, context.info)
4010                    .await
4011                    .into_value()
4012            })
4013        },
4014    );
4015    (field, validation)
4016}
4017
4018fn object_field_result_async_with_info<M, Ctx, T, A, F>(
4019    name: &'static str,
4020    resolver: F,
4021    registry: &mut TypeRegistry,
4022) -> (gql::Field, ValidationSlot<Ctx>)
4023where
4024    M: ObjectModel,
4025    Ctx: 'static,
4026    T: OutputType + IntoValue + Send + 'static,
4027    A: InputObject,
4028    F: for<'r> Fn(
4029            &'r M,
4030            A,
4031            &'r Ctx,
4032            &'r gql::ResolveInfo<'r>,
4033        ) -> BoxFuture<'r, Result<T, GraphQLError>>
4034        + Send
4035        + Sync
4036        + 'static,
4037{
4038    T::register_output(registry);
4039    A::register_args(registry);
4040    let resolver = Arc::new(resolver);
4041    let validation = ValidationSlot::new();
4042    let hook = validation.clone();
4043    let field = add_arguments::<A>(gql::Field::new(name, T::output_type()), registry).resolve(
4044        move |context| {
4045            let resolver = Arc::clone(&resolver);
4046            let hook = hook.clone();
4047            Box::pin(async move {
4048                let model = model_ref::<M>(
4049                    context.parent,
4050                    context.info.parent_type,
4051                    context.info.field_name,
4052                )?;
4053                let args = coerce_args::<A>(
4054                    context.args,
4055                    context.info.parent_type,
4056                    context.info.field_name,
4057                )?;
4058                let ctx = context.context.require_data::<Ctx>()?;
4059                hook.run(&args, ctx)?;
4060                match (resolver)(model, args, ctx, context.info).await {
4061                    Ok(value) => value.into_value(),
4062                    Err(error) => Err(error),
4063                }
4064            })
4065        },
4066    );
4067    (field, validation)
4068}
4069
4070fn object_field_with_execution<M, Ctx, T, A, F>(
4071    name: &'static str,
4072    resolver: F,
4073    registry: &mut TypeRegistry,
4074) -> (gql::Field, ValidationSlot<Ctx>)
4075where
4076    M: ObjectModel,
4077    Ctx: 'static,
4078    T: OutputType + IntoValue + Send + 'static,
4079    A: InputObject,
4080    F: for<'r> Fn(&'r M, A, &'r Ctx, &'r gql::ResolverContext<'r>) -> T + Send + Sync + 'static,
4081{
4082    T::register_output(registry);
4083    A::register_args(registry);
4084    let resolver = Arc::new(resolver);
4085    let validation = ValidationSlot::new();
4086    let hook = validation.clone();
4087    let field = add_arguments::<A>(gql::Field::new(name, T::output_type()), registry).resolve(
4088        move |context| {
4089            let resolver = Arc::clone(&resolver);
4090            let hook = hook.clone();
4091            Box::pin(async move {
4092                let model = model_ref::<M>(
4093                    context.parent,
4094                    context.info.parent_type,
4095                    context.info.field_name,
4096                )?;
4097                let args = coerce_args::<A>(
4098                    context.args,
4099                    context.info.parent_type,
4100                    context.info.field_name,
4101                )?;
4102                let ctx = context.context.require_data::<Ctx>()?;
4103                hook.run(&args, ctx)?;
4104                (resolver)(model, args, ctx, &context).into_value()
4105            })
4106        },
4107    );
4108    (field, validation)
4109}
4110
4111fn object_field_result_with_execution<M, Ctx, T, A, F>(
4112    name: &'static str,
4113    resolver: F,
4114    registry: &mut TypeRegistry,
4115) -> (gql::Field, ValidationSlot<Ctx>)
4116where
4117    M: ObjectModel,
4118    Ctx: 'static,
4119    T: OutputType + IntoValue + Send + 'static,
4120    A: InputObject,
4121    F: for<'r> Fn(&'r M, A, &'r Ctx, &'r gql::ResolverContext<'r>) -> Result<T, GraphQLError>
4122        + Send
4123        + Sync
4124        + 'static,
4125{
4126    T::register_output(registry);
4127    A::register_args(registry);
4128    let resolver = Arc::new(resolver);
4129    let validation = ValidationSlot::new();
4130    let hook = validation.clone();
4131    let field = add_arguments::<A>(gql::Field::new(name, T::output_type()), registry).resolve(
4132        move |context| {
4133            let resolver = Arc::clone(&resolver);
4134            let hook = hook.clone();
4135            Box::pin(async move {
4136                let model = model_ref::<M>(
4137                    context.parent,
4138                    context.info.parent_type,
4139                    context.info.field_name,
4140                )?;
4141                let args = coerce_args::<A>(
4142                    context.args,
4143                    context.info.parent_type,
4144                    context.info.field_name,
4145                )?;
4146                let ctx = context.context.require_data::<Ctx>()?;
4147                hook.run(&args, ctx)?;
4148                match (resolver)(model, args, ctx, &context) {
4149                    Ok(value) => value.into_value(),
4150                    Err(error) => Err(error),
4151                }
4152            })
4153        },
4154    );
4155    (field, validation)
4156}
4157
4158fn root_field_with_info<Ctx, T, A, F>(
4159    name: &'static str,
4160    resolver: F,
4161    registry: &mut TypeRegistry,
4162    register_output: bool,
4163) -> (gql::Field, ValidationSlot<Ctx>)
4164where
4165    Ctx: 'static,
4166    T: OutputType + IntoValue + Send + 'static,
4167    A: InputObject,
4168    F: for<'r> Fn(A, &'r Ctx, &'r gql::ResolveInfo<'r>) -> T + Send + Sync + 'static,
4169{
4170    if register_output {
4171        T::register_output(registry);
4172    }
4173    A::register_args(registry);
4174    let resolver = Arc::new(resolver);
4175    let validation = ValidationSlot::new();
4176    let hook = validation.clone();
4177    let field = add_arguments::<A>(gql::Field::new(name, T::output_type()), registry).resolve(
4178        move |context| {
4179            let resolver = Arc::clone(&resolver);
4180            let hook = hook.clone();
4181            Box::pin(async move {
4182                let args = coerce_args::<A>(
4183                    context.args,
4184                    context.info.parent_type,
4185                    context.info.field_name,
4186                )?;
4187                let ctx = context.context.require_data::<Ctx>()?;
4188                hook.run(&args, ctx)?;
4189                (resolver)(args, ctx, context.info).into_value()
4190            })
4191        },
4192    );
4193    (field, validation)
4194}
4195
4196fn root_field_result_with_info<Ctx, T, A, F>(
4197    name: &'static str,
4198    resolver: F,
4199    registry: &mut TypeRegistry,
4200) -> (gql::Field, ValidationSlot<Ctx>)
4201where
4202    Ctx: 'static,
4203    T: OutputType + IntoValue + Send + 'static,
4204    A: InputObject,
4205    F: for<'r> Fn(A, &'r Ctx, &'r gql::ResolveInfo<'r>) -> Result<T, GraphQLError>
4206        + Send
4207        + Sync
4208        + 'static,
4209{
4210    T::register_output(registry);
4211    A::register_args(registry);
4212    let resolver = Arc::new(resolver);
4213    let validation = ValidationSlot::new();
4214    let hook = validation.clone();
4215    let field = add_arguments::<A>(gql::Field::new(name, T::output_type()), registry).resolve(
4216        move |context| {
4217            let resolver = Arc::clone(&resolver);
4218            let hook = hook.clone();
4219            Box::pin(async move {
4220                let args = coerce_args::<A>(
4221                    context.args,
4222                    context.info.parent_type,
4223                    context.info.field_name,
4224                )?;
4225                let ctx = context.context.require_data::<Ctx>()?;
4226                hook.run(&args, ctx)?;
4227                match (resolver)(args, ctx, context.info) {
4228                    Ok(value) => value.into_value(),
4229                    Err(error) => Err(error),
4230                }
4231            })
4232        },
4233    );
4234    (field, validation)
4235}
4236
4237fn root_field_result_union_with_info<Ctx, T, E, A, F>(
4238    name: &'static str,
4239    resolver: F,
4240    registry: &mut TypeRegistry,
4241    parent: &str,
4242) -> (gql::Field, ValidationSlot<Ctx>)
4243where
4244    Ctx: 'static,
4245    T: OutputType + IntoValue + Send + 'static,
4246    E: ErrorUnionModel,
4247    A: InputObject,
4248    F: for<'r> Fn(A, &'r Ctx, &'r gql::ResolveInfo<'r>) -> core::result::Result<T, E>
4249        + Send
4250        + Sync
4251        + 'static,
4252{
4253    let ty = result_union_type_ref::<T, E>(registry, parent, name);
4254    A::register_args(registry);
4255    let resolver = Arc::new(resolver);
4256    let validation = ValidationSlot::new();
4257    let hook = validation.clone();
4258    let field = add_arguments::<A>(gql::Field::new(name, ty), registry).resolve(move |context| {
4259        let resolver = Arc::clone(&resolver);
4260        let hook = hook.clone();
4261        Box::pin(async move {
4262            let args = coerce_args::<A>(
4263                context.args,
4264                context.info.parent_type,
4265                context.info.field_name,
4266            )?;
4267            let ctx = context.context.require_data::<Ctx>()?;
4268            hook.run(&args, ctx)?;
4269            match (resolver)(args, ctx, context.info) {
4270                Ok(value) => value
4271                    .into_value()
4272                    .map(|data| gql::Value::external(ResultSuccess::new(data))),
4273                Err(error) => error.into_value(),
4274            }
4275        })
4276    });
4277    (field, validation)
4278}
4279
4280fn root_field_result_union_async_with_info<Ctx, T, E, A, F>(
4281    name: &'static str,
4282    resolver: F,
4283    registry: &mut TypeRegistry,
4284    parent: &str,
4285) -> (gql::Field, ValidationSlot<Ctx>)
4286where
4287    Ctx: 'static,
4288    T: OutputType + IntoValue + Send + 'static,
4289    E: ErrorUnionModel,
4290    A: InputObject,
4291    F: for<'r> Fn(
4292            A,
4293            &'r Ctx,
4294            &'r gql::ResolveInfo<'r>,
4295        ) -> BoxFuture<'r, core::result::Result<T, E>>
4296        + Send
4297        + Sync
4298        + 'static,
4299{
4300    let ty = result_union_type_ref::<T, E>(registry, parent, name);
4301    A::register_args(registry);
4302    let resolver = Arc::new(resolver);
4303    let validation = ValidationSlot::new();
4304    let hook = validation.clone();
4305    let field = add_arguments::<A>(gql::Field::new(name, ty), registry).resolve(move |context| {
4306        let resolver = Arc::clone(&resolver);
4307        let hook = hook.clone();
4308        Box::pin(async move {
4309            let args = coerce_args::<A>(
4310                context.args,
4311                context.info.parent_type,
4312                context.info.field_name,
4313            )?;
4314            let ctx = context.context.require_data::<Ctx>()?;
4315            hook.run(&args, ctx)?;
4316            match (resolver)(args, ctx, context.info).await {
4317                Ok(value) => value
4318                    .into_value()
4319                    .map(|data| gql::Value::external(ResultSuccess::new(data))),
4320                Err(error) => error.into_value(),
4321            }
4322        })
4323    });
4324    (field, validation)
4325}
4326
4327fn root_field_async_with_info<Ctx, T, A, F>(
4328    name: &'static str,
4329    resolver: F,
4330    registry: &mut TypeRegistry,
4331) -> (gql::Field, ValidationSlot<Ctx>)
4332where
4333    Ctx: 'static,
4334    T: OutputType + IntoValue + Send + 'static,
4335    A: InputObject,
4336    F: for<'r> Fn(A, &'r Ctx, &'r gql::ResolveInfo<'r>) -> BoxFuture<'r, T> + Send + Sync + 'static,
4337{
4338    T::register_output(registry);
4339    A::register_args(registry);
4340    let resolver = Arc::new(resolver);
4341    let validation = ValidationSlot::new();
4342    let hook = validation.clone();
4343    let field = add_arguments::<A>(gql::Field::new(name, T::output_type()), registry).resolve(
4344        move |context| {
4345            let resolver = Arc::clone(&resolver);
4346            let hook = hook.clone();
4347            Box::pin(async move {
4348                let args = coerce_args::<A>(
4349                    context.args,
4350                    context.info.parent_type,
4351                    context.info.field_name,
4352                )?;
4353                let ctx = context.context.require_data::<Ctx>()?;
4354                hook.run(&args, ctx)?;
4355                (resolver)(args, ctx, context.info).await.into_value()
4356            })
4357        },
4358    );
4359    (field, validation)
4360}
4361
4362fn root_field_result_async_with_info<Ctx, T, A, F>(
4363    name: &'static str,
4364    resolver: F,
4365    registry: &mut TypeRegistry,
4366) -> (gql::Field, ValidationSlot<Ctx>)
4367where
4368    Ctx: 'static,
4369    T: OutputType + IntoValue + Send + 'static,
4370    A: InputObject,
4371    F: for<'r> Fn(A, &'r Ctx, &'r gql::ResolveInfo<'r>) -> BoxFuture<'r, Result<T, GraphQLError>>
4372        + Send
4373        + Sync
4374        + 'static,
4375{
4376    T::register_output(registry);
4377    A::register_args(registry);
4378    let resolver = Arc::new(resolver);
4379    let validation = ValidationSlot::new();
4380    let hook = validation.clone();
4381    let field = add_arguments::<A>(gql::Field::new(name, T::output_type()), registry).resolve(
4382        move |context| {
4383            let resolver = Arc::clone(&resolver);
4384            let hook = hook.clone();
4385            Box::pin(async move {
4386                let args = coerce_args::<A>(
4387                    context.args,
4388                    context.info.parent_type,
4389                    context.info.field_name,
4390                )?;
4391                let ctx = context.context.require_data::<Ctx>()?;
4392                hook.run(&args, ctx)?;
4393                match (resolver)(args, ctx, context.info).await {
4394                    Ok(value) => value.into_value(),
4395                    Err(error) => Err(error),
4396                }
4397            })
4398        },
4399    );
4400    (field, validation)
4401}
4402
4403fn root_field_with_execution<Ctx, T, A, F>(
4404    name: &'static str,
4405    resolver: F,
4406    registry: &mut TypeRegistry,
4407) -> (gql::Field, ValidationSlot<Ctx>)
4408where
4409    Ctx: 'static,
4410    T: OutputType + IntoValue + Send + 'static,
4411    A: InputObject,
4412    F: for<'r> Fn(A, &'r Ctx, &'r gql::ResolverContext<'r>) -> T + Send + Sync + 'static,
4413{
4414    T::register_output(registry);
4415    A::register_args(registry);
4416    let resolver = Arc::new(resolver);
4417    let validation = ValidationSlot::new();
4418    let hook = validation.clone();
4419    let field = add_arguments::<A>(gql::Field::new(name, T::output_type()), registry).resolve(
4420        move |context| {
4421            let resolver = Arc::clone(&resolver);
4422            let hook = hook.clone();
4423            Box::pin(async move {
4424                let args = coerce_args::<A>(
4425                    context.args,
4426                    context.info.parent_type,
4427                    context.info.field_name,
4428                )?;
4429                let ctx = context.context.require_data::<Ctx>()?;
4430                hook.run(&args, ctx)?;
4431                (resolver)(args, ctx, &context).into_value()
4432            })
4433        },
4434    );
4435    (field, validation)
4436}
4437
4438fn root_field_result_with_execution<Ctx, T, A, F>(
4439    name: &'static str,
4440    resolver: F,
4441    registry: &mut TypeRegistry,
4442) -> (gql::Field, ValidationSlot<Ctx>)
4443where
4444    Ctx: 'static,
4445    T: OutputType + IntoValue + Send + 'static,
4446    A: InputObject,
4447    F: for<'r> Fn(A, &'r Ctx, &'r gql::ResolverContext<'r>) -> Result<T, GraphQLError>
4448        + Send
4449        + Sync
4450        + 'static,
4451{
4452    T::register_output(registry);
4453    A::register_args(registry);
4454    let resolver = Arc::new(resolver);
4455    let validation = ValidationSlot::new();
4456    let hook = validation.clone();
4457    let field = add_arguments::<A>(gql::Field::new(name, T::output_type()), registry).resolve(
4458        move |context| {
4459            let resolver = Arc::clone(&resolver);
4460            let hook = hook.clone();
4461            Box::pin(async move {
4462                let args = coerce_args::<A>(
4463                    context.args,
4464                    context.info.parent_type,
4465                    context.info.field_name,
4466                )?;
4467                let ctx = context.context.require_data::<Ctx>()?;
4468                hook.run(&args, ctx)?;
4469                match (resolver)(args, ctx, &context) {
4470                    Ok(value) => value.into_value(),
4471                    Err(error) => Err(error),
4472                }
4473            })
4474        },
4475    );
4476    (field, validation)
4477}
4478
4479fn subscription_field_result_union<Ctx, T, E, A, F, S>(
4480    name: &'static str,
4481    subscribe: F,
4482    registry: &mut TypeRegistry,
4483    parent: &str,
4484) -> (gql::Field, ValidationSlot<Ctx>)
4485where
4486    Ctx: 'static,
4487    A: InputObject,
4488    T: OutputType + IntoValue + Send + 'static,
4489    E: ErrorUnionModel,
4490    S: Stream<Item = core::result::Result<T, E>> + Send + 'static,
4491    F: for<'r> Fn(A, &'r Ctx, &'r gql::ResolveInfo<'r>) -> S + Send + Sync + 'static,
4492{
4493    let ty = result_union_type_ref::<T, E>(registry, parent, name);
4494    A::register_args(registry);
4495    let subscribe = Arc::new(subscribe);
4496    let validation = ValidationSlot::new();
4497    let hook = validation.clone();
4498    let field = add_arguments::<A>(gql::Field::new(name, ty), registry)
4499        .resolve(move |context| {
4500            let hook = hook.clone();
4501            Box::pin(async move {
4502                let args = coerce_args_without_validation::<A>(
4503                    context.args,
4504                    context.info.parent_type,
4505                    context.info.field_name,
4506                )?;
4507                let ctx = context.context.require_data::<Ctx>()?;
4508                hook.run(&args, ctx)?;
4509                context
4510                    .parent
4511                    .as_object()
4512                    .and_then(|object| object.get(context.info.field_name))
4513                    .cloned()
4514                    .ok_or_else(|| {
4515                        GraphQLError::new(format!(
4516                            "Subscription event for \"{}\" did not contain the field value.",
4517                            context.info.field_name
4518                        ))
4519                    })
4520            })
4521        })
4522        .subscribe(move |context| {
4523            let subscribe = Arc::clone(&subscribe);
4524            Box::pin(async move {
4525                let args = coerce_args::<A>(
4526                    context.args,
4527                    context.info.parent_type,
4528                    context.info.field_name,
4529                )?;
4530                let ctx = context.context.require_data::<Ctx>()?;
4531                let stream = subscribe(args, ctx, context.info);
4532                let field_name: Name = Arc::from(context.info.field_name);
4533                let mapped = stream.map(move |item| {
4534                    let value = match item {
4535                        Ok(value) => value
4536                            .into_value()
4537                            .map(|data| gql::Value::external(ResultSuccess::new(data))),
4538                        Err(error) => error.into_value(),
4539                    }?;
4540                    let mut object = gql::Object::new();
4541                    object.insert(field_name.clone(), value);
4542                    Ok(gql::Value::Object(Arc::new(object)))
4543                });
4544                Ok(Box::pin(mapped) as gql::SubscriptionStream)
4545            })
4546        });
4547    (field, validation)
4548}
4549
4550fn subscription_field<Ctx, A, T, F, S>(
4551    name: &'static str,
4552    subscribe: F,
4553    registry: &mut TypeRegistry,
4554    register_output: bool,
4555) -> (gql::Field, ValidationSlot<Ctx>)
4556where
4557    Ctx: 'static,
4558    A: InputObject,
4559    T: OutputType + IntoValue + Send + 'static,
4560    S: Stream<Item = Result<T, GraphQLError>> + Send + 'static,
4561    F: for<'r> Fn(A, &'r Ctx, &'r gql::ResolveInfo<'r>) -> S + Send + Sync + 'static,
4562{
4563    if register_output {
4564        T::register_output(registry);
4565    }
4566    A::register_args(registry);
4567    let subscribe = Arc::new(subscribe);
4568    let validation = ValidationSlot::new();
4569    let hook = validation.clone();
4570    let field = add_arguments::<A>(gql::Field::new(name, T::output_type()), registry)
4571        .resolve(move |context| {
4572            let hook = hook.clone();
4573            Box::pin(async move {
4574                // Arguments were validated once when the subscription started. Conversion still
4575                // happens per event so the field validator sees the same typed arguments, but
4576                // input-level validation is not repeated.
4577                let args = coerce_args_without_validation::<A>(
4578                    context.args,
4579                    context.info.parent_type,
4580                    context.info.field_name,
4581                )?;
4582                let ctx = context.context.require_data::<Ctx>()?;
4583                hook.run(&args, ctx)?;
4584                context
4585                    .parent
4586                    .as_object()
4587                    .and_then(|object| object.get(context.info.field_name))
4588                    .cloned()
4589                    .ok_or_else(|| {
4590                        GraphQLError::new(format!(
4591                            "Subscription event for \"{}\" did not contain the field value.",
4592                            context.info.field_name
4593                        ))
4594                    })
4595            })
4596        })
4597        .subscribe(move |context| {
4598            let subscribe = Arc::clone(&subscribe);
4599            Box::pin(async move {
4600                let args = coerce_args::<A>(
4601                    context.args,
4602                    context.info.parent_type,
4603                    context.info.field_name,
4604                )?;
4605                let ctx = context.context.require_data::<Ctx>()?;
4606                let stream = subscribe(args, ctx, context.info);
4607                let field_name: Name = Arc::from(context.info.field_name);
4608                let mapped = stream.map(move |item| match item {
4609                    Ok(value) => {
4610                        let value = value.into_value()?;
4611                        let mut object = gql::Object::new();
4612                        object.insert(field_name.clone(), value);
4613                        Ok(gql::Value::Object(Arc::new(object)))
4614                    }
4615                    Err(error) => Err(error),
4616                });
4617                Ok(Box::pin(mapped) as gql::SubscriptionStream)
4618            })
4619        });
4620    (field, validation)
4621}
4622
4623/// Whether `actual`'s wrappers are at least as strict as `declared`'s.
4624///
4625/// `actual` is what the resolver's Rust type can produce; `declared` is what the schema claims.
4626/// Every non-null position in `declared` must also be non-null in `actual`, because a `None`
4627/// would violate the schema. Nullable positions may replace non-null ones (loosening), and the
4628/// list structure must match exactly.
4629fn wrapper_compatible(actual: &TypeRef, declared: &TypeRef) -> bool {
4630    match (actual, declared) {
4631        (TypeRef::NonNull(actual), TypeRef::NonNull(declared)) => {
4632            wrapper_compatible(actual, declared)
4633        }
4634        // A non-null value satisfies a nullable declaration.
4635        (TypeRef::NonNull(actual), declared) => wrapper_compatible(actual, declared),
4636        // A value the Rust type may omit cannot satisfy a non-null declaration.
4637        (_, TypeRef::NonNull(_)) => false,
4638        (TypeRef::List(actual), TypeRef::List(declared)) => wrapper_compatible(actual, declared),
4639        (TypeRef::Named(_), TypeRef::Named(_)) => true,
4640        _ => false,
4641    }
4642}
4643
4644/// Whether a value of `actual` can be completed as `expected`.
4645///
4646/// Non-null may narrow a nullable declaration and list items may narrow the same way. A concrete
4647/// object may stand in for an abstract type that lists it as a possible type.
4648fn is_output_subtype(schema: &gql::Schema, actual: &TypeRef, expected: &TypeRef) -> bool {
4649    match (actual, expected) {
4650        (TypeRef::NonNull(actual), TypeRef::NonNull(expected)) => {
4651            is_output_subtype(schema, actual, expected)
4652        }
4653        (TypeRef::NonNull(actual), expected) => is_output_subtype(schema, actual, expected),
4654        (_, TypeRef::NonNull(_)) => false,
4655        (TypeRef::List(actual), TypeRef::List(expected)) => {
4656            is_output_subtype(schema, actual, expected)
4657        }
4658        (TypeRef::Named(actual), TypeRef::Named(expected)) => {
4659            actual == expected
4660                || (schema
4661                    .get_type(expected)
4662                    .is_some_and(|ty| matches!(ty, gql::Type::Interface(_) | gql::Type::Union(_)))
4663                    && schema.is_possible_type(expected, actual))
4664        }
4665        _ => false,
4666    }
4667}
4668
4669/// Verify that every deferred field declaration is truthful.
4670fn validate_checks(schema: &gql::Schema, checks: &[FieldCheck], errors: &mut Vec<GraphQLError>) {
4671    for check in checks {
4672        match check {
4673            FieldCheck::Abstract {
4674                owner,
4675                field,
4676                original,
4677                abstract_name,
4678            } => {
4679                let Some(abstract_type) = schema.get_type(abstract_name) else {
4680                    errors.push(GraphQLError::new(format!(
4681                        "Field `{owner}.{field}` declares unknown abstract type `{abstract_name}`."
4682                    )));
4683                    continue;
4684                };
4685                if !matches!(abstract_type, gql::Type::Interface(_) | gql::Type::Union(_)) {
4686                    errors.push(GraphQLError::new(format!(
4687                        "Field `{owner}.{field}` declares `{abstract_name}` as abstract, but it \
4688                         is a {}.",
4689                        abstract_type.kind()
4690                    )));
4691                    continue;
4692                }
4693                let original = original.named_type();
4694                if original == abstract_name {
4695                    continue;
4696                }
4697                if !schema.is_possible_type(abstract_name, original) {
4698                    errors.push(GraphQLError::new(format!(
4699                        "Field `{owner}.{field}` declares abstract type `{abstract_name}`, but \
4700                         its Rust type `{original}` is not a possible type of `{abstract_name}`."
4701                    )));
4702                }
4703            }
4704            FieldCheck::DynamicObject {
4705                owner,
4706                field,
4707                original,
4708                model,
4709            } => {
4710                if original.named_type().as_ref() != *model {
4711                    errors.push(GraphQLError::new(format!(
4712                        "Field `{owner}.{field}` declares a runtime-named object, but its Rust \
4713                         type `{original}` is not `{model}`. Resolve the object's model (or a \
4714                         `Raw<{model}>`), or pass the reference for the model that is returned."
4715                    )));
4716                }
4717            }
4718            FieldCheck::DynamicType {
4719                owner,
4720                field,
4721                rust,
4722                declared,
4723            } => {
4724                if !wrapper_compatible(rust, declared) {
4725                    errors.push(GraphQLError::new(format!(
4726                        "Field `{owner}.{field}` declares its type as `{declared}`, which is not \
4727                         compatible with the resolver's Rust type `{rust}`. The declared type \
4728                         must not make a nullable position non-null, and its list wrappers must \
4729                         match the Rust collection."
4730                    )));
4731                    continue;
4732                }
4733                let name = declared.named_type();
4734                match schema.get_type(name) {
4735                    None => errors.push(GraphQLError::new(format!(
4736                        "Field `{owner}.{field}` declares `{name}` as its type, but that type is \
4737                         not in the schema. Register it before calling `build()`."
4738                    ))),
4739                    Some(gql::Type::InputObject(_)) => errors.push(GraphQLError::new(format!(
4740                        "Field `{owner}.{field}` declares `{name}` as its output type, but it is \
4741                         an input object. Input objects cannot be used in output positions."
4742                    ))),
4743                    Some(_) => {}
4744                }
4745            }
4746            FieldCheck::TypeOverride {
4747                owner,
4748                field,
4749                original,
4750                replacement,
4751            } => {
4752                // The override may loosen nullability, but it must never claim a non-null
4753                // position the resolver can fill with `None`, and it cannot turn a list into a
4754                // scalar (or vice versa) because the resolver still returns the Rust collection.
4755                if !wrapper_compatible(original, replacement) {
4756                    errors.push(GraphQLError::new(format!(
4757                        "Field `{owner}.{field}` overrides its type from `{original}` to \
4758                         `{replacement}`, which is not compatible with the resolver's Rust type. \
4759                         The override must not make a nullable position non-null, and its list \
4760                         wrappers must match the Rust collection. Remove the `Option` or `Vec` \
4761                         from the override, or change the resolver's return type."
4762                    )));
4763                    continue;
4764                }
4765                let original_name = original.named_type();
4766                let replacement_name = replacement.named_type();
4767                if original_name == replacement_name {
4768                    continue;
4769                }
4770                let Some(original_type) = schema.get_type(original_name) else {
4771                    errors.push(GraphQLError::new(format!(
4772                        "Field `{owner}.{field}` overrides a type that is not in the schema \
4773                         (`{original_name}`). Register it before calling `build()`."
4774                    )));
4775                    continue;
4776                };
4777                let Some(replacement_type) = schema.get_type(replacement_name) else {
4778                    errors.push(GraphQLError::new(format!(
4779                        "Field `{owner}.{field}` overrides its type to `{replacement_name}`, but \
4780                         that type is not in the schema. Register it before calling `build()`."
4781                    )));
4782                    continue;
4783                };
4784                let compatible = match (original_type, replacement_type) {
4785                    (gql::Type::Scalar(_), gql::Type::Scalar(_))
4786                    | (gql::Type::Enum(_), gql::Type::Enum(_)) => true,
4787                    (gql::Type::Interface(_) | gql::Type::Union(_), _) => {
4788                        schema.is_possible_type(original_name, replacement_name)
4789                    }
4790                    (_, gql::Type::Interface(_) | gql::Type::Union(_)) => {
4791                        schema.is_possible_type(replacement_name, original_name)
4792                    }
4793                    _ => false,
4794                };
4795                if !compatible {
4796                    errors.push(GraphQLError::new(format!(
4797                        "Field `{owner}.{field}` overrides its type from `{original}` to \
4798                         `{replacement}`, but `{original_name}` and `{replacement_name}` are not \
4799                         compatible. `as_type`/`returns` can only change between scalars, between \
4800                         enums, or to and from an abstract type whose possible types include the \
4801                         Rust type."
4802                    )));
4803                }
4804            }
4805            FieldCheck::NonNullOnOption {
4806                owner,
4807                field,
4808                rust_type,
4809            } => errors.push(GraphQLError::new(format!(
4810                "Field `{owner}.{field}` calls `non_null()`, but its resolver returns \
4811                 `{rust_type}`, which is optional. Remove the call or make the Rust type \
4812                 non-optional."
4813            ))),
4814            FieldCheck::NullableItemsOnNonList { owner, field, ty } => {
4815                errors.push(GraphQLError::new(format!(
4816                    "Field `{owner}.{field}` calls `nullable_items()`, but its type `{ty}` is not \
4817                     a list. Use `nullable()` to make the field itself nullable."
4818                )));
4819            }
4820            FieldCheck::NonNullItemsOnNonList { owner, field, ty } => {
4821                errors.push(GraphQLError::new(format!(
4822                    "Field `{owner}.{field}` calls `non_null_items()`, but its type `{ty}` is not \
4823                     a list. Use `non_null()` to make the field itself non-null."
4824                )));
4825            }
4826            FieldCheck::InheritedType {
4827                owner,
4828                field,
4829                actual,
4830                expected,
4831            } => {
4832                if !is_output_subtype(schema, actual, expected) {
4833                    errors.push(GraphQLError::new(format!(
4834                        "Field `{owner}.{field}` inherits `{expected}` from its interface, but its \
4835                         resolver returns `{actual}`. Both the Rust type and the resolver's return \
4836                         type must match the interface field."
4837                    )));
4838                }
4839            }
4840        }
4841    }
4842}
4843
4844/// A type reference for tests and tooling: the GraphQL type a Rust type maps to.
4845#[must_use]
4846pub fn type_ref<T: OutputType>() -> TypeRef {
4847    T::output_type()
4848}
4849
4850/// Whether `name` matches the GraphQL `Name` grammar: `[_A-Za-z][_0-9A-Za-z]*`.
4851pub(crate) fn is_valid_graphql_name(name: &str) -> bool {
4852    let mut characters = name.chars();
4853    match characters.next() {
4854        Some(first) if first == '_' || first.is_ascii_alphabetic() => {}
4855        _ => return false,
4856    }
4857    characters.all(|character| character == '_' || character.is_ascii_alphanumeric())
4858}