1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
//! Named-type registration.
//!
//! Types are identified by name in `gql`, so the schema does not need to know a definition's
//! position to reference it. The registry collects each named definition exactly once while
//! fields and arguments are declared, then hands the set to `gql` at build time.
use std::{
any::TypeId,
collections::{HashMap, HashSet},
sync::Arc,
};
use gql::{GraphQLError, InputObjectType, Name, ObjectType, Type, UnionType};
use indexmap::IndexMap;
use crate::{
EnumModel, InputObject, ScalarValue,
traits::{AbstractType, InputType},
};
/// Collects the named GraphQL types a schema references.
///
/// A schema owns one registry. Every field, argument and expose declaration registers the types
/// it mentions; duplicate registrations of the same name are ignored, so a type can be used by
/// any number of fields without extra bookkeeping in user code.
#[derive(Clone, Debug, Default)]
pub struct TypeRegistry {
types: IndexMap<String, Type>,
/// Object names referenced by fields but registered separately by `schema.object`.
referenced_objects: HashSet<Arc<str>>,
/// Union names referenced by an output type but registered by `schema.union`.
referenced_unions: HashSet<Arc<str>>,
/// Input types currently being registered, used to stop recursion on self-referential
/// input objects.
in_progress: HashSet<String>,
/// The Rust type that owns each GraphQL name, so two different Rust types cannot silently
/// claim the same GraphQL name.
type_ids: HashMap<String, TypeId>,
/// Names for which a collision has already been reported.
conflicts: HashSet<String>,
/// Args-only Rust types that were used in a nested input position, reported once each.
unnamed_inputs: HashSet<TypeId>,
/// Objects generated by the builder itself, for example a result union's success payload.
///
/// They are kept out of `types` until `Schema::build` so they can be merged with the
/// user-declared objects before plugins and authorization run.
generated_objects: IndexMap<Name, gql::ObjectType>,
/// Unions generated by the builder itself, for example `<Parent><Field>Result`.
generated_unions: IndexMap<Name, gql::UnionType>,
/// The Rust marker type that generated each runtime-named type, so reopening or rebuilding
/// the same declaration is idempotent while a different declaration under the same name is
/// reported.
generated_ids: HashMap<Name, TypeId>,
/// Objects that a generated type depends on, with a tailored missing-registration error.
required_objects: IndexMap<String, GraphQLError>,
errors: Vec<GraphQLError>,
}
impl TypeRegistry {
/// An empty registry.
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Whether a named type has already been registered.
#[must_use]
pub fn contains(&self, name: &str) -> bool {
self.types.contains_key(name)
}
/// Record that an object type is used by an output position.
#[doc(hidden)]
pub fn reference_object(&mut self, name: impl Into<Arc<str>>) {
self.referenced_objects.insert(name.into());
}
/// Record that a union type is used by an output position.
#[doc(hidden)]
pub fn reference_union(&mut self, name: impl Into<Arc<str>>) {
self.referenced_unions.insert(name.into());
}
/// Register an enum type.
#[doc(hidden)]
pub fn register_enum<T: EnumModel>(&mut self) {
if self.already_registered(T::NAME, TypeId::of::<T>()) {
return;
}
let mut enumeration = gql::EnumType::new(T::NAME);
if let Some(description) = T::description() {
enumeration = enumeration.description(description);
}
for value in T::values() {
enumeration.values.insert(value.name.clone(), value);
}
self.type_ids.insert(T::NAME.to_owned(), TypeId::of::<T>());
self.types.insert(
T::NAME.to_owned(),
Type::Enum(std::sync::Arc::new(enumeration)),
);
}
/// Register a custom scalar type.
#[doc(hidden)]
pub fn register_scalar<T: ScalarValue>(&mut self) {
if self.already_registered(T::NAME, TypeId::of::<T>()) {
return;
}
let mut scalar = gql::ScalarType::new(T::NAME)
.serialize(|value| Ok(value.clone()))
.parse_value(|value| match T::from_value(value) {
Ok(_) => Ok(value.clone()),
Err(error) => Err(error.message().to_owned()),
})
.parse_literal(|literal| match T::from_literal(literal) {
Ok(value) => Ok(value),
Err(error) => Err(error.message().to_owned()),
});
if let Some(description) = T::description() {
scalar = scalar.description(description);
}
if let Some(url) = T::specified_by() {
scalar = scalar.specified_by_url(url);
}
self.type_ids.insert(T::NAME.to_owned(), TypeId::of::<T>());
self.types.insert(
T::NAME.to_owned(),
Type::Scalar(std::sync::Arc::new(scalar)),
);
}
/// Register a derived input object type and its fields.
#[doc(hidden)]
pub fn register_input_object<T: InputObject>(&mut self) {
let Some(name) = T::NAME else {
return;
};
if self.already_registered(name, TypeId::of::<T>()) || self.in_progress.contains(name) {
return;
}
self.in_progress.insert(name.to_owned());
let fields = match T::fields() {
Ok(fields) => fields,
Err(error) => {
self.errors.push(GraphQLError::new(format!(
"Failed to register input object `{name}`: {}",
error.message()
)));
self.in_progress.remove(name);
return;
}
};
let mut input = InputObjectType::new(name);
if let Some(description) = T::description() {
input = input.description(description);
}
if T::one_of() {
input = input.one_of();
}
for field in fields {
input.insert_field(field);
}
self.type_ids.insert(name.to_owned(), TypeId::of::<T>());
self.types.insert(
name.to_owned(),
Type::InputObject(std::sync::Arc::new(input)),
);
self.in_progress.remove(name);
}
/// Register a generated object type under a runtime name.
///
/// Used by result unions: the success payload is generated from the parent and field name,
/// not declared by the user, so it is merged into the schema during [`crate::Schema::build`].
/// Registering the same name for the same marker again is a no-op; a different marker is a
/// build error.
#[doc(hidden)]
pub(crate) fn register_generated_object<M: 'static>(&mut self, name: Name, object: ObjectType) {
if !self.claim_generated::<M>(&name, "object") {
return;
}
self.generated_objects.insert(name, object);
}
/// Register a generated union type under a runtime name. See
/// [`TypeRegistry::register_generated_object`].
#[doc(hidden)]
pub(crate) fn register_generated_union<M: 'static>(&mut self, name: Name, union: UnionType) {
if !self.claim_generated::<M>(&name, "union") {
return;
}
self.generated_unions.insert(name, union);
}
/// Claim a generated name for `M`, reporting a collision once.
fn claim_generated<M: 'static>(&mut self, name: &Name, kind: &str) -> bool {
let type_id = TypeId::of::<M>();
if let Some(existing) = self.generated_ids.get(name.as_ref()) {
if *existing == type_id {
return false;
}
if self.conflicts.insert(name.to_string()) {
self.errors.push(GraphQLError::new(format!(
"Generated {kind} `{name}` is used by two different result-union declarations. \
Give the fields distinct names, or declare one of them explicitly."
)));
}
return false;
}
if self.types.contains_key(name.as_ref()) {
if self.conflicts.insert(name.to_string()) {
self.errors.push(GraphQLError::new(format!(
"Generated {kind} `{name}` collides with a type that is already registered. \
Generated result-union names are derived from the parent type and field \
name; give the field a different name or register the type explicitly."
)));
}
return false;
}
self.generated_ids.insert(Arc::clone(name), type_id);
true
}
/// Record that a generated type depends on an object registered by the user.
///
/// The object may legitimately be registered after the field is declared, so the check runs
/// when the schema is built. The message names the field and the missing payload type, which
/// is more useful than a generic dangling reference.
#[doc(hidden)]
pub(crate) fn require_object(
&mut self,
name: &str,
owner: &str,
field: &str,
purpose: &'static str,
) {
self.required_objects
.entry(name.to_owned())
.or_insert_with(|| {
GraphQLError::new(format!(
"`{purpose}` for `{owner}.{field}` refers to object type `{name}`, which was \
never registered. Call `schema.object::<...>(...)` or \
`schema.object_ref::<...>(\"{name}\")` for every error payload type before \
calling `build()`."
))
});
}
/// Take the objects and unions generated by the builder so [`crate::Schema::build`] can
/// merge them into the user-declared maps.
pub(crate) fn take_generated(
&mut self,
) -> (IndexMap<Name, ObjectType>, IndexMap<Name, UnionType>) {
(
std::mem::take(&mut self.generated_objects),
std::mem::take(&mut self.generated_unions),
)
}
/// Take the object requirements recorded by generated types.
pub(crate) fn take_required_objects(&mut self) -> IndexMap<String, GraphQLError> {
std::mem::take(&mut self.required_objects)
}
/// Return `true` when this exact Rust type already registered the name, and record an error
/// when a different Rust type claims the same GraphQL name.
fn already_registered(&mut self, name: &str, type_id: TypeId) -> bool {
if !self.types.contains_key(name) {
return false;
}
if self.type_ids.get(name) == Some(&type_id) {
return true;
}
if self.conflicts.insert(name.to_owned()) {
self.errors.push(GraphQLError::new(format!(
"GraphQL type `{name}` is registered by more than one Rust type. Give one of them a distinct `#[graphql(name = \"...\")]`."
)));
}
true
}
/// Report an args-only [`crate::InputObject`] used where a named input type is required.
#[doc(hidden)]
pub fn unnamed_input<T: InputObject>(&mut self) {
if !self.unnamed_inputs.insert(TypeId::of::<T>()) {
return;
}
self.errors.push(GraphQLError::new(format!(
"`{}` is used as a nested input type, but it has no GraphQL name. Add \
`#[graphql(name = \"{}\")]` to make it a reusable input object, or move its fields \
into the outer input type.",
std::any::type_name::<T>(),
std::any::type_name::<T>()
.rsplit("::")
.next()
.unwrap_or("Input"),
)));
}
/// Register a field or argument's input type, and the types nested inside it.
#[doc(hidden)]
pub fn register_input<T: InputType>(&mut self) {
T::register_input(self);
}
/// Record a schema-level problem found while registering types.
pub(crate) fn push_error(&mut self, error: GraphQLError) {
self.errors.push(error);
}
/// Every error recorded while registering types.
pub(crate) fn take_errors(&mut self) -> Vec<GraphQLError> {
std::mem::take(&mut self.errors)
}
/// Whether an args-only input was used in a nested input position.
pub(crate) fn has_unnamed_input(&self) -> bool {
!self.unnamed_inputs.is_empty()
}
/// The names of object types referenced by output positions.
pub(crate) fn referenced_objects(&self) -> &HashSet<Arc<str>> {
&self.referenced_objects
}
/// The names of union types referenced by output positions.
pub(crate) fn referenced_unions(&self) -> &HashSet<Arc<str>> {
&self.referenced_unions
}
/// The named definitions registered so far.
///
/// Used by [`crate::Schema::build`] to apply directives declared before the type existed.
/// Scalars, enums and input objects live here; objects, interfaces and unions are held by the
/// schema itself.
pub(crate) fn types_mut(&mut self) -> &mut IndexMap<String, Type> {
&mut self.types
}
/// Consume the registry into its named definitions, in registration order.
pub(crate) fn into_types(self) -> IndexMap<String, Type> {
self.types
}
}
impl AbstractType for crate::schema::InterfaceRef {
fn abstract_name(&self) -> &str {
self.name()
}
}
impl AbstractType for crate::schema::UnionRef {
fn abstract_name(&self) -> &str {
self.name()
}
}