Skip to main content

juniper/types/
async_await.rs

1use std::{future, ops::ControlFlow};
2
3use auto_enums::enum_derive;
4use futures::stream::{FuturesOrdered, StreamExt as _};
5
6use crate::{
7    ast::Selection,
8    executor::{ExecutionResult, Executor},
9    parser::Spanning,
10    value::{DefaultScalarValue, Object, ScalarValue, Value},
11};
12
13use crate::BoxFuture;
14
15use super::base::{Arguments, GraphQLType, GraphQLValue, is_excluded, merge_key_into};
16
17/// Extension of [`GraphQLValue`] trait with asynchronous queries/mutations resolvers.
18///
19/// Convenience macros related to asynchronous queries/mutations expand into an implementation of
20/// this trait and [`GraphQLValue`] for the given type.
21pub trait GraphQLValueAsync<S = DefaultScalarValue>: GraphQLValue<S> + Sync
22where
23    Self::TypeInfo: Sync,
24    Self::Context: Sync,
25    S: ScalarValue + Send + Sync,
26{
27    /// Resolves the value of a single field on this [`GraphQLValueAsync`].
28    ///
29    /// The `arguments` object contains all the specified arguments, with default values being
30    /// substituted for the ones not provided by the query.
31    ///
32    /// The `executor` can be used to drive selections into sub-[objects][3].
33    ///
34    /// # Panics
35    ///
36    /// The default implementation panics.
37    ///
38    /// [3]: https://spec.graphql.org/October2021#sec-Objects
39    fn resolve_field_async<'a>(
40        &'a self,
41        _info: &'a Self::TypeInfo,
42        _field_name: &'a str,
43        _arguments: &'a Arguments<S>,
44        _executor: &'a Executor<Self::Context, S>,
45    ) -> BoxFuture<'a, ExecutionResult<S>> {
46        panic!(
47            "GraphQLValueAsync::resolve_field_async() must be implemented by objects and \
48             interfaces",
49        );
50    }
51
52    /// Resolves this [`GraphQLValueAsync`] (being an [interface][1] or an [union][2]) into a
53    /// concrete downstream [object][3] type.
54    ///
55    /// Tries to resolve this [`GraphQLValueAsync`] into the provided `type_name`. If the type
56    /// matches, then passes the instance along to [`Executor::resolve`].
57    ///
58    /// # Panics
59    ///
60    /// The default implementation panics.
61    ///
62    /// [1]: https://spec.graphql.org/October2021#sec-Interfaces
63    /// [2]: https://spec.graphql.org/October2021#sec-Unions
64    /// [3]: https://spec.graphql.org/October2021#sec-Objects
65    fn resolve_into_type_async<'a>(
66        &'a self,
67        info: &'a Self::TypeInfo,
68        type_name: &str,
69        selection_set: Option<&'a [Selection<'a, S>]>,
70        executor: &'a Executor<'a, 'a, Self::Context, S>,
71    ) -> BoxFuture<'a, ExecutionResult<S>> {
72        if self.type_name(info).unwrap() == type_name {
73            self.resolve_async(info, selection_set, executor)
74        } else {
75            panic!(
76                "GraphQLValueAsync::resolve_into_type_async() must be implemented by unions and \
77                 interfaces",
78            );
79        }
80    }
81
82    /// Resolves the provided `selection_set` against this [`GraphQLValueAsync`].
83    ///
84    /// For non-[object][3] types, the `selection_set` will be [`None`] and the value should simply
85    /// be returned.
86    ///
87    /// For [objects][3], all fields in the `selection_set` should be resolved. The default
88    /// implementation uses [`GraphQLValueAsync::resolve_field_async`] to resolve all fields,
89    /// including those through a fragment expansion.
90    ///
91    /// Since the [GraphQL spec specifies][0] that errors during field processing should result in
92    /// a null-value, this might return `Ok(Null)` in case of a failure. Errors are recorded
93    /// internally.
94    ///
95    /// # Panics
96    ///
97    /// The default implementation panics, if `selection_set` is [`None`].
98    ///
99    /// [0]: https://spec.graphql.org/October2021#sec-Handling-Field-Errors
100    /// [3]: https://spec.graphql.org/October2021#sec-Objects
101    fn resolve_async<'a>(
102        &'a self,
103        info: &'a Self::TypeInfo,
104        selection_set: Option<&'a [Selection<S>]>,
105        executor: &'a Executor<Self::Context, S>,
106    ) -> BoxFuture<'a, ExecutionResult<S>> {
107        if let Some(sel) = selection_set {
108            Box::pin(async move {
109                Ok(resolve_selection_set_into_async(self, info, sel, executor).await)
110            })
111        } else {
112            panic!(
113                "GraphQLValueAsync::resolve_async() must be implemented by non-object output types",
114            );
115        }
116    }
117}
118
119/// Extension of [`GraphQLType`] trait with asynchronous queries/mutations resolvers.
120///
121/// It's automatically implemented for [`GraphQLValueAsync`] and [`GraphQLType`] implementers, so
122/// doesn't require manual or code-generated implementation.
123pub trait GraphQLTypeAsync<S = DefaultScalarValue>: GraphQLValueAsync<S> + GraphQLType<S>
124where
125    Self::Context: Sync,
126    Self::TypeInfo: Sync,
127    S: ScalarValue + Send + Sync,
128{
129}
130
131impl<S, T> GraphQLTypeAsync<S> for T
132where
133    T: GraphQLValueAsync<S> + GraphQLType<S> + ?Sized,
134    T::Context: Sync,
135    T::TypeInfo: Sync,
136    S: ScalarValue + Send + Sync,
137{
138}
139
140// Wrapper function around resolve_selection_set_into_async_recursive.
141// This wrapper is necessary because async fns can not be recursive.
142fn resolve_selection_set_into_async<'a, 'e, T, S>(
143    instance: &'a T,
144    info: &'a T::TypeInfo,
145    selection_set: &'e [Selection<'e, S>],
146    executor: &'e Executor<'e, 'e, T::Context, S>,
147) -> BoxFuture<'a, Value<S>>
148where
149    T: GraphQLValueAsync<S> + ?Sized,
150    T::TypeInfo: Sync,
151    T::Context: Sync,
152    S: ScalarValue + Send + Sync,
153    'e: 'a,
154{
155    Box::pin(resolve_selection_set_into_async_recursive(
156        instance,
157        info,
158        selection_set,
159        executor,
160    ))
161}
162
163#[derive(Debug)]
164struct AsyncField<S> {
165    name: String,
166    value: Option<Value<S>>,
167}
168
169#[derive(Debug)]
170enum AsyncValue<S> {
171    Field(AsyncField<S>),
172    Nested(Value<S>),
173}
174
175pub(crate) async fn resolve_selection_set_into_async_recursive<'a, T, S>(
176    instance: &'a T,
177    info: &'a T::TypeInfo,
178    selection_set: &'a [Selection<'a, S>],
179    executor: &'a Executor<'a, 'a, T::Context, S>,
180) -> Value<S>
181where
182    T: GraphQLValueAsync<S> + ?Sized,
183    T::TypeInfo: Sync,
184    T::Context: Sync,
185    S: ScalarValue + Send + Sync,
186{
187    #[enum_derive(Future)]
188    enum AsyncValueFuture<F1, F2, FS, IF1, IF2> {
189        Field1(F1),
190        Field2(F2),
191        FragmentSpread(FS),
192        InlineFragment1(IF1),
193        InlineFragment2(IF2),
194    }
195
196    let mut object = Object::with_capacity(selection_set.len());
197
198    let mut async_values = FuturesOrdered::<AsyncValueFuture<_, _, _, _, _>>::new();
199
200    let meta_type = executor
201        .schema()
202        .concrete_type_by_name(
203            instance
204                .type_name(info)
205                .expect("Resolving named type's selection set"),
206        )
207        .expect("Type not found in schema");
208
209    for selection in selection_set {
210        match *selection {
211            Selection::Field(Spanning {
212                item: ref f,
213                ref span,
214            }) => {
215                if is_excluded(&f.directives, executor.variables()) {
216                    continue;
217                }
218
219                let response_name = f.alias.as_ref().unwrap_or(&f.name).item;
220
221                if f.name.item == "__typename" {
222                    object.add_field(
223                        response_name,
224                        Value::Scalar(instance.concrete_type_name(executor.context(), info).into()),
225                    );
226                    continue;
227                }
228
229                let meta_field = meta_type.field_by_name(f.name.item).unwrap_or_else(|| {
230                    panic!(
231                        "Field {} not found on type {:?}",
232                        f.name.item,
233                        meta_type.name(),
234                    )
235                });
236
237                let exec_vars = executor.variables();
238
239                let sub_exec = executor.field_sub_executor(
240                    response_name,
241                    f.name.item,
242                    span.start,
243                    f.selection_set.as_ref().map(|v| &v[..]),
244                );
245                let args = Arguments::new(
246                    f.arguments.as_ref().map(|m| {
247                        m.item
248                            .iter()
249                            .filter_map(|(k, v)| {
250                                let val = v.item.clone().into_const(exec_vars)?;
251                                Some((k.item, Spanning::new(v.span, val)))
252                            })
253                            .collect()
254                    }),
255                    &meta_field.arguments,
256                );
257
258                let pos = span.start;
259                let is_non_null = meta_field.field_type.is_non_null();
260
261                let response_name = response_name.to_string();
262                async_values.push_back(AsyncValueFuture::Field1(async move {
263                    // TODO: implement custom future type instead of
264                    //       two-level boxing.
265                    let res = instance
266                        .resolve_field_async(info, f.name.item, &args, &sub_exec)
267                        .await;
268
269                    let value = match res {
270                        Ok(Value::Null) if is_non_null => {
271                            sub_exec.push_non_null_violation_at(meta_type, f.name.item, pos);
272                            None
273                        }
274                        Ok(v) => Some(v),
275                        Err(e) => {
276                            sub_exec.push_error_at(e, pos);
277
278                            if is_non_null {
279                                None
280                            } else {
281                                Some(Value::null())
282                            }
283                        }
284                    };
285                    AsyncValue::Field(AsyncField {
286                        name: response_name,
287                        value,
288                    })
289                }));
290            }
291
292            Selection::FragmentSpread(Spanning {
293                item: ref spread,
294                ref span,
295            }) => {
296                if is_excluded(&spread.directives, executor.variables()) {
297                    continue;
298                }
299
300                let fragment = &executor
301                    .fragment_by_name(spread.name.item)
302                    .expect("Fragment could not be found");
303
304                let sub_exec = executor.type_sub_executor(
305                    Some(fragment.type_condition.item),
306                    Some(&fragment.selection_set[..]),
307                );
308
309                let concrete_type_name = instance.concrete_type_name(sub_exec.context(), info);
310                let type_name = instance.type_name(info);
311                if executor
312                    .schema()
313                    .is_named_subtype(&concrete_type_name, fragment.type_condition.item)
314                    || Some(fragment.type_condition.item) == type_name.as_deref()
315                {
316                    let sub_result = instance
317                        .resolve_into_type_async(
318                            info,
319                            &concrete_type_name,
320                            Some(&fragment.selection_set[..]),
321                            &sub_exec,
322                        )
323                        .await;
324
325                    if let Ok(Value::Object(obj)) = sub_result {
326                        for (k, v) in obj {
327                            async_values.push_back(AsyncValueFuture::FragmentSpread(
328                                future::ready(AsyncValue::Field(AsyncField {
329                                    name: k,
330                                    value: Some(v),
331                                })),
332                            ));
333                        }
334                    } else {
335                        if let Err(e) = sub_result {
336                            sub_exec.push_error_at(e, span.start);
337                        }
338                        // NOTE: Executing a fragment cannot really result in anything other
339                        //       than `Value::Object`, because it represents a set of fields.
340                        //       So, if an error happens or a `Value::Null` is returned, it's an
341                        //       indication that the fragment execution failed somewhere and,
342                        //       because of non-`null` types involved, its error should be
343                        //       propagated to the parent field, which is done here by returning
344                        //       a `Value::Null`.
345                        async_values.push_back(AsyncValueFuture::Field2(future::ready(
346                            AsyncValue::Field(AsyncField {
347                                name: String::new(), // doesn't matter here
348                                value: None,
349                            }),
350                        )));
351                    }
352                }
353            }
354
355            Selection::InlineFragment(Spanning {
356                item: ref fragment,
357                ref span,
358            }) => {
359                if is_excluded(&fragment.directives, executor.variables()) {
360                    continue;
361                }
362
363                let sub_exec = executor.type_sub_executor(
364                    fragment.type_condition.as_ref().map(|c| c.item),
365                    Some(&fragment.selection_set[..]),
366                );
367
368                if let Some(ref type_condition) = fragment.type_condition {
369                    // Check whether the type matches the type condition.
370                    let concrete_type_name = instance.concrete_type_name(sub_exec.context(), info);
371                    if executor
372                        .schema()
373                        .is_named_subtype(&concrete_type_name, type_condition.item)
374                    {
375                        let sub_result = instance
376                            .resolve_into_type_async(
377                                info,
378                                &concrete_type_name,
379                                Some(&fragment.selection_set[..]),
380                                &sub_exec,
381                            )
382                            .await;
383
384                        if let Ok(Value::Object(obj)) = sub_result {
385                            for (k, v) in obj {
386                                async_values.push_back(AsyncValueFuture::InlineFragment1(
387                                    future::ready(AsyncValue::Field(AsyncField {
388                                        name: k,
389                                        value: Some(v),
390                                    })),
391                                ));
392                            }
393                        } else {
394                            if let Err(e) = sub_result {
395                                sub_exec.push_error_at(e, span.start);
396                            }
397                            // NOTE: Executing a fragment cannot really result in anything other
398                            //       than `Value::Object`, because it represents a set of fields.
399                            //       So, if an error happens or a `Value::Null` is returned, it's an
400                            //       indication that the fragment execution failed somewhere and,
401                            //       because of non-`null` types involved, its error should be
402                            //       propagated to the parent field, which is done here by returning
403                            //       a `Value::Null`.
404                            async_values.push_back(AsyncValueFuture::Field2(future::ready(
405                                AsyncValue::Field(AsyncField {
406                                    name: String::new(), // doesn't matter here
407                                    value: None,
408                                }),
409                            )));
410                        }
411                    }
412                } else {
413                    async_values.push_back(AsyncValueFuture::InlineFragment2(async move {
414                        let value = resolve_selection_set_into_async(
415                            instance,
416                            info,
417                            &fragment.selection_set[..],
418                            &sub_exec,
419                        )
420                        .await;
421                        AsyncValue::Nested(value)
422                    }));
423                }
424            }
425        }
426
427        // In serial execution, each selection completes before the next selection starts.
428        if executor.is_serial()
429            && merge_async_values(&mut async_values, &mut object)
430                .await
431                .is_break()
432        {
433            return Value::null();
434        }
435    }
436
437    if merge_async_values(&mut async_values, &mut object)
438        .await
439        .is_break()
440    {
441        return Value::null();
442    }
443
444    Value::Object(object)
445}
446
447/// Awaits the `values` in order and merges them into `object`.
448///
449/// Returns [`ControlFlow::Break`] for a field without a value or for a `null` nested object. Both
450/// come from a `null` in a non-null field. The `null` then replaces the whole `object`.
451async fn merge_async_values<F, S>(
452    values: &mut FuturesOrdered<F>,
453    object: &mut Object<S>,
454) -> ControlFlow<()>
455where
456    F: Future<Output = AsyncValue<S>>,
457{
458    while let Some(value) = values.next().await {
459        match value {
460            AsyncValue::Field(AsyncField {
461                name,
462                value: Some(value),
463            }) => merge_key_into(object, &name, value),
464            AsyncValue::Field(AsyncField { value: None, .. }) | AsyncValue::Nested(Value::Null) => {
465                return ControlFlow::Break(());
466            }
467            AsyncValue::Nested(Value::Object(nested)) => {
468                for (name, value) in nested {
469                    merge_key_into(object, &name, value);
470                }
471            }
472            AsyncValue::Nested(_) => unreachable!(),
473        }
474    }
475    ControlFlow::Continue(())
476}