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
17pub trait GraphQLValueAsync<S = DefaultScalarValue>: GraphQLValue<S> + Sync
22where
23 Self::TypeInfo: Sync,
24 Self::Context: Sync,
25 S: ScalarValue + Send + Sync,
26{
27 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 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 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
119pub 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
140fn 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 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 async_values.push_back(AsyncValueFuture::Field2(future::ready(
346 AsyncValue::Field(AsyncField {
347 name: String::new(), 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 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 async_values.push_back(AsyncValueFuture::Field2(future::ready(
405 AsyncValue::Field(AsyncField {
406 name: String::new(), 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 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
447async 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}