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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
use std::{any::Any, collections::HashMap, fmt::Debug, sync::Arc};

use async_graphql_parser::types::OperationType;
use futures_util::{stream::BoxStream, Stream, StreamExt, TryFutureExt};
use indexmap::IndexMap;

use crate::{
    dynamic::{
        field::BoxResolverFn, r#type::Type, resolve::resolve_container, FieldFuture, FieldValue,
        Object, ResolverContext, Scalar, SchemaError, Subscription,
    },
    extensions::{ExtensionFactory, Extensions},
    registry::{MetaType, Registry},
    schema::{prepare_request, SchemaEnvInner},
    Data, Executor, IntrospectionMode, QueryEnv, Request, Response, SDLExportOptions, SchemaEnv,
    ServerError, ServerResult, ValidationMode,
};

/// Dynamic schema builder
pub struct SchemaBuilder {
    query_type: String,
    mutation_type: Option<String>,
    subscription_type: Option<String>,
    types: IndexMap<String, Type>,
    data: Data,
    extensions: Vec<Box<dyn ExtensionFactory>>,
    validation_mode: ValidationMode,
    recursive_depth: usize,
    complexity: Option<usize>,
    depth: Option<usize>,
    enable_suggestions: bool,
    introspection_mode: IntrospectionMode,
    enable_federation: bool,
    entity_resolver: Option<BoxResolverFn>,
}

impl SchemaBuilder {
    /// Register a GraphQL type
    #[must_use]
    pub fn register(mut self, ty: impl Into<Type>) -> Self {
        let ty = ty.into();
        self.types.insert(ty.name().to_string(), ty);
        self
    }

    /// Add a global data that can be accessed in the `Schema`. You access it
    /// with `Context::data`.
    #[must_use]
    pub fn data<D: Any + Send + Sync>(mut self, data: D) -> Self {
        self.data.insert(data);
        self
    }

    /// Add an extension to the schema.
    #[must_use]
    pub fn extension(mut self, extension: impl ExtensionFactory) -> Self {
        self.extensions.push(Box::new(extension));
        self
    }

    /// Set the maximum complexity a query can have. By default, there is no
    /// limit.
    #[must_use]
    pub fn limit_complexity(mut self, complexity: usize) -> Self {
        self.complexity = Some(complexity);
        self
    }

    /// Set the maximum depth a query can have. By default, there is no limit.
    #[must_use]
    pub fn limit_depth(mut self, depth: usize) -> Self {
        self.depth = Some(depth);
        self
    }

    /// Set the maximum recursive depth a query can have. (default: 32)
    ///
    /// If the value is too large, stack overflow may occur, usually `32` is
    /// enough.
    #[must_use]
    pub fn limit_recursive_depth(mut self, depth: usize) -> Self {
        self.recursive_depth = depth;
        self
    }

    /// Set the validation mode, default is `ValidationMode::Strict`.
    #[must_use]
    pub fn validation_mode(mut self, validation_mode: ValidationMode) -> Self {
        self.validation_mode = validation_mode;
        self
    }

    /// Disable field suggestions.
    #[must_use]
    pub fn disable_suggestions(mut self) -> Self {
        self.enable_suggestions = false;
        self
    }

    /// Disable introspection queries.
    #[must_use]
    pub fn disable_introspection(mut self) -> Self {
        self.introspection_mode = IntrospectionMode::Disabled;
        self
    }

    /// Only process introspection queries, everything else is processed as an
    /// error.
    #[must_use]
    pub fn introspection_only(mut self) -> Self {
        self.introspection_mode = IntrospectionMode::IntrospectionOnly;
        self
    }

    /// Enable federation, which is automatically enabled if the Query has least
    /// one entity definition.
    #[must_use]
    pub fn enable_federation(mut self) -> Self {
        self.enable_federation = true;
        self
    }

    /// Set the entity resolver for federation
    pub fn entity_resolver<F>(self, resolver_fn: F) -> Self
    where
        F: for<'a> Fn(ResolverContext<'a>) -> FieldFuture<'a> + Send + Sync + 'static,
    {
        Self {
            entity_resolver: Some(Box::new(resolver_fn)),
            ..self
        }
    }

    /// Consumes this builder and returns a schema.
    pub fn finish(mut self) -> Result<Schema, SchemaError> {
        let mut registry = Registry {
            types: Default::default(),
            directives: Default::default(),
            implements: Default::default(),
            query_type: self.query_type,
            mutation_type: self.mutation_type,
            subscription_type: self.subscription_type,
            introspection_mode: self.introspection_mode,
            enable_federation: false,
            federation_subscription: false,
            ignore_name_conflicts: Default::default(),
            enable_suggestions: self.enable_suggestions,
        };
        registry.add_system_types();

        for ty in self.types.values() {
            ty.register(&mut registry)?;
        }
        update_interface_possible_types(&mut self.types, &mut registry);

        // create system scalars
        for ty in ["Int", "Float", "Boolean", "String", "ID"] {
            self.types
                .insert(ty.to_string(), Type::Scalar(Scalar::new(ty)));
        }

        // create introspection types
        if matches!(
            self.introspection_mode,
            IntrospectionMode::Enabled | IntrospectionMode::IntrospectionOnly
        ) {
            registry.create_introspection_types();
        }

        // create entity types
        if self.enable_federation || registry.has_entities() {
            registry.enable_federation = true;
            registry.create_federation_types();
        }

        let inner = SchemaInner {
            env: SchemaEnv(Arc::new(SchemaEnvInner {
                registry,
                data: self.data,
                custom_directives: Default::default(),
            })),
            extensions: self.extensions,
            types: self.types,
            recursive_depth: self.recursive_depth,
            complexity: self.complexity,
            depth: self.depth,
            validation_mode: self.validation_mode,
            entity_resolver: self.entity_resolver,
        };
        inner.check()?;
        Ok(Schema(Arc::new(inner)))
    }
}

/// Dyanmic GraphQL schema.
///
/// Cloning a schema is cheap, so it can be easily shared.
#[derive(Clone)]
pub struct Schema(pub(crate) Arc<SchemaInner>);

impl Debug for Schema {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Schema").finish()
    }
}

pub struct SchemaInner {
    pub(crate) env: SchemaEnv,
    pub(crate) types: IndexMap<String, Type>,
    extensions: Vec<Box<dyn ExtensionFactory>>,
    recursive_depth: usize,
    complexity: Option<usize>,
    depth: Option<usize>,
    validation_mode: ValidationMode,
    pub(crate) entity_resolver: Option<BoxResolverFn>,
}

impl Schema {
    /// Create a schema builder
    pub fn build(query: &str, mutation: Option<&str>, subscription: Option<&str>) -> SchemaBuilder {
        SchemaBuilder {
            query_type: query.to_string(),
            mutation_type: mutation.map(ToString::to_string),
            subscription_type: subscription.map(ToString::to_string),
            types: Default::default(),
            data: Default::default(),
            extensions: Default::default(),
            validation_mode: ValidationMode::Strict,
            recursive_depth: 32,
            complexity: None,
            depth: None,
            enable_suggestions: true,
            introspection_mode: IntrospectionMode::Enabled,
            entity_resolver: None,
            enable_federation: false,
        }
    }

    fn create_extensions(&self, session_data: Arc<Data>) -> Extensions {
        Extensions::new(
            self.0.extensions.iter().map(|f| f.create()),
            self.0.env.clone(),
            session_data,
        )
    }

    fn query_root(&self) -> ServerResult<&Object> {
        self.0
            .types
            .get(&self.0.env.registry.query_type)
            .and_then(Type::as_object)
            .ok_or_else(|| ServerError::new("Query root not found", None))
    }

    fn mutation_root(&self) -> ServerResult<&Object> {
        self.0
            .env
            .registry
            .mutation_type
            .as_ref()
            .and_then(|mutation_name| self.0.types.get(mutation_name))
            .and_then(Type::as_object)
            .ok_or_else(|| ServerError::new("Mutation root not found", None))
    }

    fn subscription_root(&self) -> ServerResult<&Subscription> {
        self.0
            .env
            .registry
            .subscription_type
            .as_ref()
            .and_then(|subscription_name| self.0.types.get(subscription_name))
            .and_then(Type::as_subscription)
            .ok_or_else(|| ServerError::new("Subscription root not found", None))
    }

    /// Returns SDL(Schema Definition Language) of this schema.
    pub fn sdl(&self) -> String {
        self.0.env.registry.export_sdl(Default::default())
    }

    /// Returns SDL(Schema Definition Language) of this schema with options.
    pub fn sdl_with_options(&self, options: SDLExportOptions) -> String {
        self.0.env.registry.export_sdl(options)
    }

    async fn execute_once(&self, env: QueryEnv) -> Response {
        // execute
        let ctx = env.create_context(&self.0.env, None, &env.operation.node.selection_set);
        let res = match &env.operation.node.ty {
            OperationType::Query => {
                async move { self.query_root() }
                    .and_then(|query_root| {
                        resolve_container(self, query_root, &ctx, &FieldValue::NULL, false)
                    })
                    .await
            }
            OperationType::Mutation => {
                async move { self.mutation_root() }
                    .and_then(|query_root| {
                        resolve_container(self, query_root, &ctx, &FieldValue::NULL, true)
                    })
                    .await
            }
            OperationType::Subscription => Err(ServerError::new(
                "Subscriptions are not supported on this transport.",
                None,
            )),
        };

        let mut resp = match res {
            Ok(value) => Response::new(value.unwrap_or_default()),
            Err(err) => Response::from_errors(vec![err]),
        }
        .http_headers(std::mem::take(&mut *env.http_headers.lock().unwrap()));

        resp.errors
            .extend(std::mem::take(&mut *env.errors.lock().unwrap()));
        resp
    }

    /// Execute a GraphQL query.
    pub async fn execute(&self, request: impl Into<Request>) -> Response {
        let request = request.into();
        let extensions = self.create_extensions(Default::default());
        let request_fut = {
            let extensions = extensions.clone();
            async move {
                match prepare_request(
                    extensions,
                    request,
                    Default::default(),
                    &self.0.env.registry,
                    self.0.validation_mode,
                    self.0.recursive_depth,
                    self.0.complexity,
                    self.0.depth,
                )
                .await
                {
                    Ok((env, cache_control)) => {
                        let fut = async {
                            self.execute_once(env.clone())
                                .await
                                .cache_control(cache_control)
                        };
                        futures_util::pin_mut!(fut);
                        env.extensions
                            .execute(env.operation_name.as_deref(), &mut fut)
                            .await
                    }
                    Err(errors) => Response::from_errors(errors),
                }
            }
        };
        futures_util::pin_mut!(request_fut);
        extensions.request(&mut request_fut).await
    }

    /// Execute a GraphQL subscription with session data.
    pub fn execute_stream_with_session_data(
        &self,
        request: impl Into<Request>,
        session_data: Arc<Data>,
    ) -> impl Stream<Item = Response> + Send + Unpin {
        let schema = self.clone();
        let request = request.into();
        let extensions = self.create_extensions(session_data.clone());

        let stream = {
            let extensions = extensions.clone();

            async_stream::stream! {
                let subscription = match schema.subscription_root() {
                    Ok(subscription) => subscription,
                    Err(err) => {
                        yield Response::from_errors(vec![err]);
                        return;
                    }
                };

                let (env, _) = match prepare_request(
                    extensions,
                    request,
                    session_data,
                    &schema.0.env.registry,
                    schema.0.validation_mode,
                    schema.0.recursive_depth,
                    schema.0.complexity,
                    schema.0.depth,
                )
                .await {
                    Ok(res) => res,
                    Err(errors) => {
                        yield Response::from_errors(errors);
                        return;
                    }
                };

                if env.operation.node.ty != OperationType::Subscription {
                    yield schema.execute_once(env).await;
                    return;
                }

                let ctx = env.create_context(
                    &schema.0.env,
                    None,
                    &env.operation.node.selection_set,
                );
                let mut streams = Vec::new();
                subscription.collect_streams(&schema, &ctx, &mut streams);

                let mut stream = futures_util::stream::select_all(streams);
                while let Some(resp) = stream.next().await {
                    yield resp;
                }
            }
        };
        extensions.subscribe(stream.boxed())
    }

    /// Execute a GraphQL subscription.
    pub fn execute_stream(
        &self,
        request: impl Into<Request>,
    ) -> impl Stream<Item = Response> + Send + Unpin {
        self.execute_stream_with_session_data(request, Default::default())
    }
}

#[async_trait::async_trait]
impl Executor for Schema {
    async fn execute(&self, request: Request) -> Response {
        Schema::execute(self, request).await
    }

    fn execute_stream(
        &self,
        request: Request,
        session_data: Option<Arc<Data>>,
    ) -> BoxStream<'static, Response> {
        Schema::execute_stream_with_session_data(self, request, session_data.unwrap_or_default())
            .boxed()
    }
}

fn update_interface_possible_types(types: &mut IndexMap<String, Type>, registry: &mut Registry) {
    let mut interfaces = registry
        .types
        .values_mut()
        .filter_map(|ty| match ty {
            MetaType::Interface {
                ref name,
                possible_types,
                ..
            } => Some((name, possible_types)),
            _ => None,
        })
        .collect::<HashMap<_, _>>();

    let objs = types.values().filter_map(|ty| match ty {
        Type::Object(obj) => Some((&obj.name, &obj.implements)),
        _ => None,
    });

    for (obj_name, implements) in objs {
        for interface in implements {
            if let Some(possible_types) = interfaces.get_mut(interface) {
                possible_types.insert(obj_name.clone());
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use async_graphql_parser::{types::ExecutableDocument, Pos};
    use async_graphql_value::Variables;
    use futures_util::{stream::BoxStream, StreamExt};
    use tokio::sync::Mutex;

    use crate::{
        dynamic::*, extensions::*, value, PathSegment, Request, Response, ServerError,
        ServerResult, ValidationResult, Value,
    };

    #[tokio::test]
    async fn basic_query() {
        let myobj = Object::new("MyObj")
            .field(Field::new("a", TypeRef::named(TypeRef::INT), |_| {
                FieldFuture::new(async { Ok(Some(Value::from(123))) })
            }))
            .field(Field::new("b", TypeRef::named(TypeRef::STRING), |_| {
                FieldFuture::new(async { Ok(Some(Value::from("abc"))) })
            }));

        let query = Object::new("Query")
            .field(Field::new("value", TypeRef::named(TypeRef::INT), |_| {
                FieldFuture::new(async { Ok(Some(Value::from(100))) })
            }))
            .field(Field::new(
                "valueObj",
                TypeRef::named_nn(myobj.type_name()),
                |_| FieldFuture::new(async { Ok(Some(FieldValue::NULL)) }),
            ));
        let schema = Schema::build("Query", None, None)
            .register(query)
            .register(myobj)
            .finish()
            .unwrap();

        assert_eq!(
            schema
                .execute("{ value valueObj { a b } }")
                .await
                .into_result()
                .unwrap()
                .data,
            value!({
                "value": 100,
                "valueObj": {
                    "a": 123,
                    "b": "abc",
                }
            })
        );
    }

    #[tokio::test]
    async fn field_alias() {
        let query =
            Object::new("Query").field(Field::new("value", TypeRef::named(TypeRef::INT), |_| {
                FieldFuture::new(async { Ok(Some(Value::from(100))) })
            }));
        let schema = Schema::build("Query", None, None)
            .register(query)
            .finish()
            .unwrap();

        assert_eq!(
            schema
                .execute("{ a: value }")
                .await
                .into_result()
                .unwrap()
                .data,
            value!({
                "a": 100,
            })
        );
    }

    #[tokio::test]
    async fn fragment_spread() {
        let myobj = Object::new("MyObj")
            .field(Field::new("a", TypeRef::named(TypeRef::INT), |_| {
                FieldFuture::new(async { Ok(Some(Value::from(123))) })
            }))
            .field(Field::new("b", TypeRef::named(TypeRef::STRING), |_| {
                FieldFuture::new(async { Ok(Some(Value::from("abc"))) })
            }));

        let query = Object::new("Query").field(Field::new(
            "valueObj",
            TypeRef::named_nn(myobj.type_name()),
            |_| FieldFuture::new(async { Ok(Some(Value::Null)) }),
        ));
        let schema = Schema::build("Query", None, None)
            .register(query)
            .register(myobj)
            .finish()
            .unwrap();

        let query = r#"
            fragment A on MyObj {
                a b
            }

            { valueObj { ... A } }
            "#;

        assert_eq!(
            schema.execute(query).await.into_result().unwrap().data,
            value!({
                "valueObj": {
                    "a": 123,
                    "b": "abc",
                }
            })
        );
    }

    #[tokio::test]
    async fn inline_fragment() {
        let myobj = Object::new("MyObj")
            .field(Field::new("a", TypeRef::named(TypeRef::INT), |_| {
                FieldFuture::new(async { Ok(Some(Value::from(123))) })
            }))
            .field(Field::new("b", TypeRef::named(TypeRef::STRING), |_| {
                FieldFuture::new(async { Ok(Some(Value::from("abc"))) })
            }));

        let query = Object::new("Query").field(Field::new(
            "valueObj",
            TypeRef::named_nn(myobj.type_name()),
            |_| FieldFuture::new(async { Ok(Some(FieldValue::NULL)) }),
        ));
        let schema = Schema::build("Query", None, None)
            .register(query)
            .register(myobj)
            .finish()
            .unwrap();

        let query = r#"
            {
                valueObj {
                     ... on MyObj { a }
                     ... { b }
                }
            }
            "#;

        assert_eq!(
            schema.execute(query).await.into_result().unwrap().data,
            value!({
                "valueObj": {
                    "a": 123,
                    "b": "abc",
                }
            })
        );
    }

    #[tokio::test]
    async fn non_null() {
        let query = Object::new("Query")
            .field(Field::new(
                "valueA",
                TypeRef::named_nn(TypeRef::INT),
                |_| FieldFuture::new(async { Ok(FieldValue::none()) }),
            ))
            .field(Field::new(
                "valueB",
                TypeRef::named_nn(TypeRef::INT),
                |_| FieldFuture::new(async { Ok(Some(Value::from(100))) }),
            ))
            .field(Field::new("valueC", TypeRef::named(TypeRef::INT), |_| {
                FieldFuture::new(async { Ok(FieldValue::none()) })
            }))
            .field(Field::new("valueD", TypeRef::named(TypeRef::INT), |_| {
                FieldFuture::new(async { Ok(Some(Value::from(200))) })
            }));
        let schema = Schema::build("Query", None, None)
            .register(query)
            .finish()
            .unwrap();

        assert_eq!(
            schema
                .execute("{ valueA }")
                .await
                .into_result()
                .unwrap_err(),
            vec![ServerError {
                message: "internal: non-null types require a return value".to_owned(),
                source: None,
                locations: vec![Pos { column: 3, line: 1 }],
                path: vec![PathSegment::Field("valueA".to_owned())],
                extensions: None,
            }]
        );

        assert_eq!(
            schema
                .execute("{ valueB }")
                .await
                .into_result()
                .unwrap()
                .data,
            value!({
                "valueB": 100
            })
        );

        assert_eq!(
            schema
                .execute("{ valueC valueD }")
                .await
                .into_result()
                .unwrap()
                .data,
            value!({
                "valueC": null,
                "valueD": 200,
            })
        );
    }

    #[tokio::test]
    async fn list() {
        let query = Object::new("Query")
            .field(Field::new(
                "values",
                TypeRef::named_nn_list_nn(TypeRef::INT),
                |_| {
                    FieldFuture::new(async {
                        Ok(Some(vec![Value::from(3), Value::from(6), Value::from(9)]))
                    })
                },
            ))
            .field(Field::new(
                "values2",
                TypeRef::named_nn_list_nn(TypeRef::INT),
                |_| {
                    FieldFuture::new(async {
                        Ok(Some(Value::List(vec![
                            Value::from(3),
                            Value::from(6),
                            Value::from(9),
                        ])))
                    })
                },
            ));
        let schema = Schema::build("Query", None, None)
            .register(query)
            .finish()
            .unwrap();

        assert_eq!(
            schema
                .execute("{ values values2 }")
                .await
                .into_result()
                .unwrap()
                .data,
            value!({
                "values": [3, 6, 9],
                "values2": [3, 6, 9],
            })
        );
    }

    #[tokio::test]
    async fn extensions() {
        struct MyExtensionImpl {
            calls: Arc<Mutex<Vec<&'static str>>>,
        }

        #[async_trait::async_trait]
        #[allow(unused_variables)]
        impl Extension for MyExtensionImpl {
            async fn request(&self, ctx: &ExtensionContext<'_>, next: NextRequest<'_>) -> Response {
                self.calls.lock().await.push("request_start");
                let res = next.run(ctx).await;
                self.calls.lock().await.push("request_end");
                res
            }

            fn subscribe<'s>(
                &self,
                ctx: &ExtensionContext<'_>,
                mut stream: BoxStream<'s, Response>,
                next: NextSubscribe<'_>,
            ) -> BoxStream<'s, Response> {
                let calls = self.calls.clone();
                next.run(
                    ctx,
                    Box::pin(async_stream::stream! {
                        calls.lock().await.push("subscribe_start");
                        while let Some(item) = stream.next().await {
                            yield item;
                        }
                        calls.lock().await.push("subscribe_end");
                    }),
                )
            }

            async fn prepare_request(
                &self,
                ctx: &ExtensionContext<'_>,
                request: Request,
                next: NextPrepareRequest<'_>,
            ) -> ServerResult<Request> {
                self.calls.lock().await.push("prepare_request_start");
                let res = next.run(ctx, request).await;
                self.calls.lock().await.push("prepare_request_end");
                res
            }

            async fn parse_query(
                &self,
                ctx: &ExtensionContext<'_>,
                query: &str,
                variables: &Variables,
                next: NextParseQuery<'_>,
            ) -> ServerResult<ExecutableDocument> {
                self.calls.lock().await.push("parse_query_start");
                let res = next.run(ctx, query, variables).await;
                self.calls.lock().await.push("parse_query_end");
                res
            }

            async fn validation(
                &self,
                ctx: &ExtensionContext<'_>,
                next: NextValidation<'_>,
            ) -> Result<ValidationResult, Vec<ServerError>> {
                self.calls.lock().await.push("validation_start");
                let res = next.run(ctx).await;
                self.calls.lock().await.push("validation_end");
                res
            }

            async fn execute(
                &self,
                ctx: &ExtensionContext<'_>,
                operation_name: Option<&str>,
                next: NextExecute<'_>,
            ) -> Response {
                assert_eq!(operation_name, Some("Abc"));
                self.calls.lock().await.push("execute_start");
                let res = next.run(ctx, operation_name).await;
                self.calls.lock().await.push("execute_end");
                res
            }

            async fn resolve(
                &self,
                ctx: &ExtensionContext<'_>,
                info: ResolveInfo<'_>,
                next: NextResolve<'_>,
            ) -> ServerResult<Option<Value>> {
                self.calls.lock().await.push("resolve_start");
                let res = next.run(ctx, info).await;
                self.calls.lock().await.push("resolve_end");
                res
            }
        }

        struct MyExtension {
            calls: Arc<Mutex<Vec<&'static str>>>,
        }

        impl ExtensionFactory for MyExtension {
            fn create(&self) -> Arc<dyn Extension> {
                Arc::new(MyExtensionImpl {
                    calls: self.calls.clone(),
                })
            }
        }

        {
            let query = Object::new("Query")
                .field(Field::new(
                    "value1",
                    TypeRef::named_nn(TypeRef::INT),
                    |_| FieldFuture::new(async { Ok(Some(Value::from(10))) }),
                ))
                .field(Field::new(
                    "value2",
                    TypeRef::named_nn(TypeRef::INT),
                    |_| FieldFuture::new(async { Ok(Some(Value::from(10))) }),
                ));

            let calls: Arc<Mutex<Vec<&'static str>>> = Default::default();
            let schema = Schema::build(query.type_name(), None, None)
                .register(query)
                .extension(MyExtension {
                    calls: calls.clone(),
                })
                .finish()
                .unwrap();

            let _ = schema
                .execute("query Abc { value1 value2 }")
                .await
                .into_result()
                .unwrap();
            let calls = calls.lock().await;
            assert_eq!(
                &*calls,
                &vec![
                    "request_start",
                    "prepare_request_start",
                    "prepare_request_end",
                    "parse_query_start",
                    "parse_query_end",
                    "validation_start",
                    "validation_end",
                    "execute_start",
                    "resolve_start",
                    "resolve_end",
                    "resolve_start",
                    "resolve_end",
                    "execute_end",
                    "request_end",
                ]
            );
        }

        {
            let query = Object::new("Query").field(Field::new(
                "value1",
                TypeRef::named_nn(TypeRef::INT),
                |_| FieldFuture::new(async { Ok(Some(Value::from(10))) }),
            ));

            let subscription = Subscription::new("Subscription").field(SubscriptionField::new(
                "value",
                TypeRef::named_nn(TypeRef::INT),
                |_| {
                    SubscriptionFieldFuture::new(async {
                        Ok(futures_util::stream::iter([1, 2, 3])
                            .map(|value| Ok(Value::from(value))))
                    })
                },
            ));

            let calls: Arc<Mutex<Vec<&'static str>>> = Default::default();
            let schema = Schema::build(query.type_name(), None, Some(subscription.type_name()))
                .register(query)
                .register(subscription)
                .extension(MyExtension {
                    calls: calls.clone(),
                })
                .finish()
                .unwrap();

            let mut stream = schema.execute_stream("subscription Abc { value }");
            while stream.next().await.is_some() {}
            let calls = calls.lock().await;
            assert_eq!(
                &*calls,
                &vec![
                    "subscribe_start",
                    "prepare_request_start",
                    "prepare_request_end",
                    "parse_query_start",
                    "parse_query_end",
                    "validation_start",
                    "validation_end",
                    // push 1
                    "execute_start",
                    "resolve_start",
                    "resolve_end",
                    "execute_end",
                    // push 2
                    "execute_start",
                    "resolve_start",
                    "resolve_end",
                    "execute_end",
                    // push 3
                    "execute_start",
                    "resolve_start",
                    "resolve_end",
                    "execute_end",
                    // end
                    "subscribe_end",
                ]
            );
        }
    }
}