apollo-router 1.61.13

A configurable, high-performance routing runtime for Apollo Federation 🚀
Documentation
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
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
use apollo_router::graphql::Request;
use insta::assert_yaml_snapshot;
use itertools::Itertools;
use tower::BoxError;
use wiremock::ResponseTemplate;

use crate::integration::ValueExt as _;

const CONFIG: &str = include_str!("../fixtures/batching/all_enabled.router.yaml");
const SHORT_TIMEOUTS_CONFIG: &str = include_str!("../fixtures/batching/short_timeouts.router.yaml");

fn test_is_enabled() -> bool {
    std::env::var("TEST_APOLLO_KEY").is_ok() && std::env::var("TEST_APOLLO_GRAPH_REF").is_ok()
}

#[tokio::test(flavor = "multi_thread")]
async fn it_supports_single_subgraph_batching() -> Result<(), BoxError> {
    const REQUEST_COUNT: usize = 5;

    let requests: Vec<_> = (0..REQUEST_COUNT)
        .map(|index| {
            Request::fake_builder()
                .query(format!(
                    "query op{index}{{ entryA(count: {REQUEST_COUNT}) {{ index }} }}"
                ))
                .build()
        })
        .collect();
    let responses = helper::run_test(
        CONFIG,
        &requests[..],
        Some(helper::expect_batch),
        None::<helper::Handler>,
    )
    .await?;

    if test_is_enabled() {
        // Make sure that we got back what we wanted
        assert_yaml_snapshot!(responses, @r###"
    ---
    - data:
        entryA:
          index: 0
    - data:
        entryA:
          index: 1
    - data:
        entryA:
          index: 2
    - data:
        entryA:
          index: 3
    - data:
        entryA:
          index: 4
    "###);
    }

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn it_supports_multi_subgraph_batching() -> Result<(), BoxError> {
    const REQUEST_COUNT: usize = 3;

    let requests_a = (0..REQUEST_COUNT).map(|index| {
        Request::fake_builder()
            .query(format!(
                "query op{index}{{ entryA(count: {REQUEST_COUNT}) {{ index }} }}"
            ))
            .build()
    });
    let requests_b = (0..REQUEST_COUNT).map(|index| {
        Request::fake_builder()
            .query(format!(
                "query op{index}{{ entryB(count: {REQUEST_COUNT}) {{ index }} }}"
            ))
            .build()
    });

    // Interleave requests so that we can verify that they get properly separated
    let requests: Vec<_> = requests_a.interleave(requests_b).collect();
    let responses = helper::run_test(
        CONFIG,
        &requests,
        Some(helper::expect_batch),
        Some(helper::expect_batch),
    )
    .await?;

    if test_is_enabled() {
        // Make sure that we got back what we wanted
        assert_yaml_snapshot!(responses, @r###"
    ---
    - data:
        entryA:
          index: 0
    - data:
        entryB:
          index: 0
    - data:
        entryA:
          index: 1
    - data:
        entryB:
          index: 1
    - data:
        entryA:
          index: 2
    - data:
        entryB:
          index: 2
    "###);
    }

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn it_batches_with_errors_in_single_graph() -> Result<(), BoxError> {
    const REQUEST_COUNT: usize = 4;

    let requests: Vec<_> = (0..REQUEST_COUNT)
        .map(|index| {
            Request::fake_builder()
                .query(format!(
                    "query op{index}{{ entryA(count: {REQUEST_COUNT}) {{ index }} }}"
                ))
                .build()
        })
        .collect();
    let responses = helper::run_test(
        CONFIG,
        &requests[..],
        Some(helper::fail_second_batch_request),
        None::<helper::Handler>,
    )
    .await?;

    if test_is_enabled() {
        // Make sure that we got back what we wanted
        assert_yaml_snapshot!(responses, @r###"
        ---
        - data:
            entryA:
              index: 0
        - errors:
            - message: expected error in A
              path: []
              extensions:
                service: a
        - data:
            entryA:
              index: 2
        - data:
            entryA:
              index: 3
        "###);
    }

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn it_batches_with_errors_in_multi_graph() -> Result<(), BoxError> {
    const REQUEST_COUNT: usize = 3;

    let requests_a = (0..REQUEST_COUNT).map(|index| {
        Request::fake_builder()
            .query(format!(
                "query op{index}{{ entryA(count: {REQUEST_COUNT}) {{ index }} }}"
            ))
            .build()
    });
    let requests_b = (0..REQUEST_COUNT).map(|index| {
        Request::fake_builder()
            .query(format!(
                "query op{index}{{ entryB(count: {REQUEST_COUNT}) {{ index }} }}"
            ))
            .build()
    });

    // Interleave requests so that we can verify that they get properly separated
    let requests: Vec<_> = requests_a.interleave(requests_b).collect();
    let responses = helper::run_test(
        CONFIG,
        &requests,
        Some(helper::fail_second_batch_request),
        Some(helper::fail_second_batch_request),
    )
    .await?;

    if test_is_enabled() {
        assert_yaml_snapshot!(responses, @r###"
        ---
        - data:
            entryA:
              index: 0
        - data:
            entryB:
              index: 0
        - errors:
            - message: expected error in A
              path: []
              extensions:
                service: a
        - errors:
            - message: expected error in B
              path: []
              extensions:
                service: b
        - data:
            entryA:
              index: 2
        - data:
            entryB:
              index: 2
        "###);
    }

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn it_handles_short_timeouts() -> Result<(), BoxError> {
    const REQUEST_COUNT: usize = 2;

    let requests_a = (0..REQUEST_COUNT).map(|index| {
        Request::fake_builder()
            .query(format!(
                "query op{index}{{ entryA(count: {REQUEST_COUNT}) {{ index }} }}"
            ))
            .build()
    });
    let requests_b = (0..REQUEST_COUNT).map(|index| {
        Request::fake_builder()
            .query(format!(
                "query op{index}{{ entryB(count: {REQUEST_COUNT}) {{ index }} }}"
            ))
            .build()
    });

    // Interleave requests so that we can verify that they get properly separated
    // Have the B subgraph timeout
    let requests: Vec<_> = requests_a.interleave(requests_b).collect();
    let responses = helper::run_test(
        SHORT_TIMEOUTS_CONFIG,
        &requests,
        Some(helper::expect_batch),
        Some(helper::never_respond),
    )
    .await?;

    if test_is_enabled() {
        assert_yaml_snapshot!(responses, @r###"
        ---
        - data:
            entryA:
              index: 0
        - errors:
            - message: Request timed out
              path: []
              extensions:
                code: REQUEST_TIMEOUT
                service: b
        - data:
            entryA:
              index: 1
        - errors:
            - message: Request timed out
              path: []
              extensions:
                code: REQUEST_TIMEOUT
                service: b
        "###);
    }

    Ok(())
}

// This test makes two simultaneous requests to the router, with the first
// being never resolved. This is to make sure that the router doesn't hang while
// processing a separate batch request.
#[tokio::test(flavor = "multi_thread")]
async fn it_handles_indefinite_timeouts() -> Result<(), BoxError> {
    const REQUEST_COUNT: usize = 3;

    let requests_a: Vec<_> = (0..REQUEST_COUNT)
        .map(|index| {
            Request::fake_builder()
                .query(format!(
                    "query op{index}{{ entryA(count: {REQUEST_COUNT}) {{ index }} }}"
                ))
                .build()
        })
        .collect();
    let requests_b: Vec<_> = (0..REQUEST_COUNT)
        .map(|index| {
            Request::fake_builder()
                .query(format!(
                    "query op{index}{{ entryB(count: {REQUEST_COUNT}) {{ index }} }}"
                ))
                .build()
        })
        .collect();

    let responses_a = helper::run_test(
        SHORT_TIMEOUTS_CONFIG,
        &requests_a,
        Some(helper::expect_batch),
        None::<helper::Handler>,
    );
    let responses_b = helper::run_test(
        SHORT_TIMEOUTS_CONFIG,
        &requests_b,
        None::<helper::Handler>,
        Some(helper::never_respond),
    );

    // Run both requests simultaneously
    let (results_a, results_b) = futures::try_join!(responses_a, responses_b)?;

    // verify the output
    let responses = [results_a, results_b].concat();
    if test_is_enabled() {
        assert_yaml_snapshot!(responses, @r###"
        ---
        - data:
            entryA:
              index: 0
        - data:
            entryA:
              index: 1
        - data:
            entryA:
              index: 2
        - errors:
            - message: Request timed out
              path: []
              extensions:
                code: REQUEST_TIMEOUT
                service: b
        - errors:
            - message: Request timed out
              path: []
              extensions:
                code: REQUEST_TIMEOUT
                service: b
        - errors:
            - message: Request timed out
              path: []
              extensions:
                code: REQUEST_TIMEOUT
                service: b
        "###);
    }

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn it_handles_cancelled_by_rhai() -> Result<(), BoxError> {
    const REQUEST_COUNT: usize = 2;
    const RHAI_CONFIG: &str = include_str!("../fixtures/batching/rhai_script.router.yaml");

    let requests_a = (0..REQUEST_COUNT).map(|index| {
        Request::fake_builder()
            .query(format!(
                "query op{index}{{ entryA(count: {REQUEST_COUNT}) {{ index }} }}"
            ))
            .build()
    });
    let requests_b = (0..REQUEST_COUNT).map(|index| {
        Request::fake_builder()
            .query(format!(
                "query op{index}_failMe{{ entryB(count: {REQUEST_COUNT}) {{ index }} }}"
            ))
            .build()
    });

    // Interleave requests so that we can verify that they get properly separated
    // Have the B subgraph get all of its requests cancelled by a rhai script
    let requests: Vec<_> = requests_a.interleave(requests_b).collect();
    let responses = helper::run_test(
        RHAI_CONFIG,
        &requests,
        Some(helper::expect_batch),
        None::<helper::Handler>,
    )
    .await?;

    if test_is_enabled() {
        assert_yaml_snapshot!(responses, @r###"
    ---
    - data:
        entryA:
          index: 0
    - errors:
        - message: "rhai execution error: 'Runtime error: cancelled expected failure (line 5, position 13)'"
    - data:
        entryA:
          index: 1
    - errors:
        - message: "rhai execution error: 'Runtime error: cancelled expected failure (line 5, position 13)'"
    "###);
    }

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn it_handles_single_request_cancelled_by_rhai() -> Result<(), BoxError> {
    const REQUEST_COUNT: usize = 2;
    const RHAI_CONFIG: &str = include_str!("../fixtures/batching/rhai_script.router.yaml");

    let requests_a = (0..REQUEST_COUNT).map(|index| {
        Request::fake_builder()
            .query(format!(
                "query op{index}{{ entryA(count: {REQUEST_COUNT}) {{ index }} }}"
            ))
            .build()
    });
    let requests_b = (0..REQUEST_COUNT).map(|index| {
        Request::fake_builder()
            .query(format!(
                "query {}{{ entryB(count: {REQUEST_COUNT}) {{ index }} }}",
                (index == 1)
                    .then_some("failMe".to_string())
                    .unwrap_or(format!("op{index}"))
            ))
            .build()
    });

    // Custom validation for subgraph B
    fn handle_b(request: &wiremock::Request) -> ResponseTemplate {
        let requests: Vec<Request> = request.body_json().unwrap();

        // We should have gotten all of the regular elements minus the second
        assert_eq!(requests.len(), REQUEST_COUNT - 1);

        // Each element should have be for the specified subgraph and should have a field selection
        // of index. The index should be 0..n without 1.
        // Note: The router appends info to the query, so we append it at this check
        for (request, index) in requests.into_iter().zip((0..).filter(|&i| i != 1)) {
            assert_eq!(
                request.query,
                Some(format!(
                    "query op{index}__b__0 {{ entryB(count: {REQUEST_COUNT}) {{ index }} }}",
                ))
            );
        }

        ResponseTemplate::new(200).set_body_json(
            (0..REQUEST_COUNT)
                .filter(|&i| i != 1)
                .map(|index| {
                    serde_json::json!({
                        "data": {
                            "entryB": {
                                "index": index
                            }
                        }
                    })
                })
                .collect::<Vec<_>>(),
        )
    }

    // Interleave requests so that we can verify that they get properly separated
    // Have the B subgraph get all of its requests cancelled by a rhai script
    let requests: Vec<_> = requests_a.interleave(requests_b).collect();
    let responses = helper::run_test(
        RHAI_CONFIG,
        &requests,
        Some(helper::expect_batch),
        Some(handle_b),
    )
    .await?;

    if test_is_enabled() {
        assert_yaml_snapshot!(responses, @r###"
    ---
    - data:
        entryA:
          index: 0
    - data:
        entryB:
          index: 0
    - data:
        entryA:
          index: 1
    - errors:
        - message: "rhai execution error: 'Runtime error: cancelled expected failure (line 5, position 13)'"
    "###);
    }

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn it_handles_cancelled_by_coprocessor() -> Result<(), BoxError> {
    const REQUEST_COUNT: usize = 2;
    const COPROCESSOR_CONFIG: &str = include_str!("../fixtures/batching/coprocessor.router.yaml");

    let requests_a = (0..REQUEST_COUNT).map(|index| {
        Request::fake_builder()
            .query(format!(
                "query op{index}{{ entryA(count: {REQUEST_COUNT}) {{ index }} }}"
            ))
            .build()
    });
    let requests_b = (0..REQUEST_COUNT).map(|index| {
        Request::fake_builder()
            .query(format!(
                "query op{index}{{ entryB(count: {REQUEST_COUNT}) {{ index }} }}"
            ))
            .build()
    });

    // Spin up a coprocessor for cancelling requests to A
    let coprocessor = wiremock::MockServer::builder().start().await;
    let subgraph_a_canceller = wiremock::Mock::given(wiremock::matchers::method("POST"))
        .respond_with(|request: &wiremock::Request| {
            let info: serde_json::Value = request.body_json().unwrap();
            let subgraph = info
                .as_object()
                .unwrap()
                .get("serviceName")
                .unwrap()
                .as_string()
                .unwrap();

            // Pass through the request if the subgraph isn't 'A'
            let response = if subgraph != "a" {
                info
            } else {
                // Patch it otherwise to stop execution
                let mut res = info;
                let block = res.as_object_mut().unwrap();
                block.insert("control".to_string(), serde_json::json!({ "break": 403 }));
                block.insert(
                    "body".to_string(),
                    serde_json::json!({
                        "errors": [{
                            "message": "Subgraph A is not allowed",
                            "extensions": {
                                "code": "ERR_NOT_ALLOWED",
                            },
                        }],
                    }),
                );

                res
            };
            ResponseTemplate::new(200).set_body_json(response)
        })
        .named("coprocessor POST /");
    coprocessor.register(subgraph_a_canceller).await;

    // Make sure to patch the config with the coprocessor's port
    let config = COPROCESSOR_CONFIG.replace("REPLACEME", &coprocessor.address().port().to_string());

    // Interleave requests so that we can verify that they get properly separated
    // Have the A subgraph get all of its requests cancelled by a coprocessor
    let requests: Vec<_> = requests_a.interleave(requests_b).collect();
    let responses = helper::run_test(
        config.as_str(),
        &requests,
        None::<helper::Handler>,
        Some(helper::expect_batch),
    )
    .await?;

    if test_is_enabled() {
        assert_yaml_snapshot!(responses, @r###"
        ---
        - errors:
            - message: Subgraph A is not allowed
              path: []
              extensions:
                code: ERR_NOT_ALLOWED
                service: a
        - data:
            entryB:
              index: 0
        - errors:
            - message: Subgraph A is not allowed
              path: []
              extensions:
                code: ERR_NOT_ALLOWED
                service: a
        - data:
            entryB:
              index: 1
        "###);
    }

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn it_handles_single_request_cancelled_by_coprocessor() -> Result<(), BoxError> {
    const REQUEST_COUNT: usize = 4;
    const COPROCESSOR_CONFIG: &str = include_str!("../fixtures/batching/coprocessor.router.yaml");

    let requests_a = (0..REQUEST_COUNT).map(|index| {
        Request::fake_builder()
            .query(format!(
                "query op{index}{{ entryA(count: {REQUEST_COUNT}) {{ index }} }}"
            ))
            .build()
    });
    let requests_b = (0..REQUEST_COUNT).map(|index| {
        Request::fake_builder()
            .query(format!(
                "query op{index}{{ entryB(count: {REQUEST_COUNT}) {{ index }} }}"
            ))
            .build()
    });

    // Spin up a coprocessor for cancelling requests to A
    let coprocessor = wiremock::MockServer::builder().start().await;
    let subgraph_a_canceller = wiremock::Mock::given(wiremock::matchers::method("POST"))
        .respond_with(|request: &wiremock::Request| {
            let info: serde_json::Value = request.body_json().unwrap();
            let subgraph = info
                .as_object()
                .unwrap()
                .get("serviceName")
                .unwrap()
                .as_string()
                .unwrap();
            let query = info
                .as_object()
                .unwrap()
                .get("body")
                .unwrap()
                .as_object()
                .unwrap()
                .get("query")
                .unwrap()
                .as_string()
                .unwrap();

            // Cancel the request if we're in subgraph A, index 2
            let response = if subgraph == "a" && query.contains("op2") {
                // Patch it to stop execution
                let mut res = info;
                let block = res.as_object_mut().unwrap();
                block.insert("control".to_string(), serde_json::json!({ "break": 403 }));
                block.insert(
                    "body".to_string(),
                    serde_json::json!({
                        "errors": [{
                            "message": "Subgraph A index 2 is not allowed",
                            "extensions": {
                                "code": "ERR_NOT_ALLOWED",
                            },
                        }],
                    }),
                );

                res
            } else {
                info
            };
            ResponseTemplate::new(200).set_body_json(response)
        })
        .named("coprocessor POST /");
    coprocessor.register(subgraph_a_canceller).await;

    // We aren't expecting the whole batch anymore, so we need a handler here for it
    fn handle_a(request: &wiremock::Request) -> ResponseTemplate {
        let requests: Vec<Request> = request.body_json().unwrap();

        // We should have gotten all of the regular elements minus the third
        assert_eq!(requests.len(), REQUEST_COUNT - 1);

        // Each element should have be for the specified subgraph and should have a field selection
        // of index. The index should be 0..n without 2.
        // Note: The router appends info to the query, so we append it at this check
        for (request, index) in requests.into_iter().zip((0..).filter(|&i| i != 2)) {
            assert_eq!(
                request.query,
                Some(format!(
                    "query op{index}__a__0 {{ entryA(count: {REQUEST_COUNT}) {{ index }} }}",
                ))
            );
        }

        ResponseTemplate::new(200).set_body_json(
            (0..REQUEST_COUNT)
                .filter(|&i| i != 2)
                .map(|index| {
                    serde_json::json!({
                        "data": {
                            "entryA": {
                                "index": index
                            }
                        }
                    })
                })
                .collect::<Vec<_>>(),
        )
    }

    // Make sure to patch the config with the coprocessor's port
    let config = COPROCESSOR_CONFIG.replace("REPLACEME", &coprocessor.address().port().to_string());

    // Interleave requests so that we can verify that they get properly separated
    // Have the A subgraph get all of its requests cancelled by a coprocessor
    let requests: Vec<_> = requests_a.interleave(requests_b).collect();
    let responses = helper::run_test(
        config.as_str(),
        &requests,
        Some(handle_a),
        Some(helper::expect_batch),
    )
    .await?;

    if test_is_enabled() {
        assert_yaml_snapshot!(responses, @r###"
        ---
        - data:
            entryA:
              index: 0
        - data:
            entryB:
              index: 0
        - data:
            entryA:
              index: 1
        - data:
            entryB:
              index: 1
        - errors:
            - message: Subgraph A index 2 is not allowed
              path: []
              extensions:
                code: ERR_NOT_ALLOWED
                service: a
        - data:
            entryB:
              index: 2
        - data:
            entryA:
              index: 3
        - data:
            entryB:
              index: 3
        "###);
    }

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn it_handles_single_invalid_graphql() -> Result<(), BoxError> {
    const REQUEST_COUNT: usize = 5;

    let mut requests: Vec<_> = (0..REQUEST_COUNT)
        .map(|index| {
            Request::fake_builder()
                .query(format!(
                    "query op{index}{{ entryA(count: {REQUEST_COUNT}) {{ index }} }}"
                ))
                .build()
        })
        .collect();

    // Mess up the 4th one
    requests[3].query = Some("query op3".into());

    // We aren't expecting the whole batch anymore, so we need a handler here for it
    fn handle_a(request: &wiremock::Request) -> ResponseTemplate {
        let requests: Vec<Request> = request.body_json().unwrap();

        // We should have gotten all of the regular elements minus the third
        assert_eq!(requests.len(), REQUEST_COUNT - 1);

        // Each element should have be for the specified subgraph and should have a field selection
        // of index. The index should be 0..n without 3.
        // Note: The router appends info to the query, so we append it at this check
        for (request, index) in requests.into_iter().zip((0..).filter(|&i| i != 3)) {
            assert_eq!(
                request.query,
                Some(format!(
                    "query op{index}__a__0 {{ entryA(count: {REQUEST_COUNT}) {{ index }} }}",
                ))
            );
        }

        ResponseTemplate::new(200).set_body_json(
            (0..REQUEST_COUNT)
                .filter(|&i| i != 3)
                .map(|index| {
                    serde_json::json!({
                        "data": {
                            "entryA": {
                                "index": index
                            }
                        }
                    })
                })
                .collect::<Vec<_>>(),
        )
    }

    let responses = helper::run_test(
        CONFIG,
        &requests[..],
        Some(handle_a),
        None::<helper::Handler>,
    )
    .await?;

    if test_is_enabled() {
        // Make sure that we got back what we wanted
        assert_yaml_snapshot!(responses, @r###"
        ---
        - data:
            entryA:
              index: 0
        - data:
            entryA:
              index: 1
        - data:
            entryA:
              index: 2
        - errors:
            - message: "parsing error: syntax error: expected a Selection Set"
              locations:
                - line: 1
                  column: 10
              extensions:
                code: PARSING_ERROR
        - data:
            entryA:
              index: 4
        "###);
    }

    Ok(())
}

/// Utility methods for these tests
mod helper {
    use std::time::Duration;

    use apollo_router::graphql::Request;
    use apollo_router::graphql::Response;
    use tower::BoxError;
    use wiremock::MockServer;
    use wiremock::Respond;
    use wiremock::ResponseTemplate;
    use wiremock::matchers;

    use super::test_is_enabled;
    use crate::integration::common::IntegrationTest;
    use crate::integration::common::Query;

    /// Helper type for specifying a valid handler
    pub type Handler = fn(&wiremock::Request) -> ResponseTemplate;

    /// Helper method for creating a wiremock handler from a handler
    ///
    /// If the handler is `None`, then the fallback is to always fail any request to the mock server
    macro_rules! make_handler {
        ($subgraph_path:expr, $handler:expr) => {
            if let Some(f) = $handler {
                wiremock::Mock::given(matchers::method("POST"))
                    .and(matchers::path($subgraph_path))
                    .respond_with(f)
                    .expect(1)
                    .named(stringify!(batching POST $subgraph_path))
            } else {
                wiremock::Mock::given(matchers::method("POST"))
                    .and(matchers::path($subgraph_path))
                    .respond_with(always_fail)
                    .expect(0)
                    .named(stringify!(batching POST $subgraph_path))
            }
        }
    }

    /// Set up the integration test stack
    pub async fn run_test<A: Respond + 'static, B: Respond + 'static>(
        config: &str,
        requests: &[Request],
        handler_a: Option<A>,
        handler_b: Option<B>,
    ) -> Result<Vec<Response>, BoxError> {
        // Ensure that we have the test keys before running
        // Note: The [IntegrationTest] ensures that these test credentials get
        // set before running the router.
        if !test_is_enabled() {
            return Ok(Vec::new());
        };

        // Create a wiremock server for each handler
        let mock_server_a = MockServer::start().await;
        let mock_server_b = MockServer::start().await;
        mock_server_a.register(make_handler!("/a", handler_a)).await;
        mock_server_b.register(make_handler!("/b", handler_b)).await;

        // Start up the router with the mocked subgraphs
        let mut router = IntegrationTest::builder()
            .config(config)
            .supergraph("tests/fixtures/batching/schema.graphql")
            .subgraph_override("a", format!("{}/a", mock_server_a.uri()))
            .subgraph_override("b", format!("{}/b", mock_server_b.uri()))
            .build()
            .await;

        router.start().await;
        router.assert_started().await;

        // Execute the request
        let request = serde_json::to_value(requests)?;
        let (_span, response) = router
            .execute_query(Query::builder().body(request).build())
            .await;

        serde_json::from_slice::<Vec<Response>>(&response.bytes().await?).map_err(BoxError::from)
    }

    /// Subgraph handler for receiving a batch of requests
    pub fn expect_batch(request: &wiremock::Request) -> ResponseTemplate {
        let requests: Vec<Request> = request.body_json().unwrap();

        // Extract info about this operation
        let (subgraph, count): (String, usize) = {
            let re = regex::Regex::new(r"entry([AB])\(count: ?([0-9]+)\)").unwrap();
            let captures = re.captures(requests[0].query.as_ref().unwrap()).unwrap();

            (captures[1].to_string(), captures[2].parse().unwrap())
        };

        // We should have gotten `count` elements
        assert_eq!(requests.len(), count);

        // Each element should have be for the specified subgraph and should have a field selection
        // of index.
        // Note: The router appends info to the query, so we append it at this check
        for (index, request) in requests.into_iter().enumerate() {
            assert_eq!(
                request.query,
                Some(format!(
                    "query op{index}__{}__0 {{ entry{}(count: {count}) {{ index }} }}",
                    subgraph.to_lowercase(),
                    subgraph
                ))
            );
        }

        ResponseTemplate::new(200).set_body_json(
            (0..count)
                .map(|index| {
                    serde_json::json!({
                        "data": {
                            format!("entry{subgraph}"): {
                                "index": index
                            }
                        }
                    })
                })
                .collect::<Vec<_>>(),
        )
    }

    /// Handler that always returns an error for the second batch field
    pub fn fail_second_batch_request(request: &wiremock::Request) -> ResponseTemplate {
        let requests: Vec<Request> = request.body_json().unwrap();

        // Extract info about this operation
        let (subgraph, count): (String, usize) = {
            let re = regex::Regex::new(r"entry([AB])\(count: ?([0-9]+)\)").unwrap();
            let captures = re.captures(requests[0].query.as_ref().unwrap()).unwrap();

            (captures[1].to_string(), captures[2].parse().unwrap())
        };

        // We should have gotten `count` elements
        assert_eq!(requests.len(), count);

        // Create the response with the second element as an error
        let responses = {
            let mut rs: Vec<_> = (0..count)
                .map(|index| {
                    serde_json::json!({
                        "data": {
                            format!("entry{subgraph}"): {
                                "index": index
                            }
                        }
                    })
                })
                .collect();

            rs[1] = serde_json::json!({ "errors": [{ "message": format!("expected error in {subgraph}") }] });
            rs
        };

        // Respond with an error on the second element but valid data for the rest
        ResponseTemplate::new(200).set_body_json(responses)
    }

    /// Subgraph handler that delays indefinitely
    ///
    /// Useful for testing timeouts at the batch level
    pub fn never_respond(request: &wiremock::Request) -> ResponseTemplate {
        let requests: Vec<Request> = request.body_json().unwrap();

        // Extract info about this operation
        let (_, count): (String, usize) = {
            let re = regex::Regex::new(r"entry([AB])\(count: ?([0-9]+)\)").unwrap();
            let captures = re.captures(requests[0].query.as_ref().unwrap()).unwrap();

            (captures[1].to_string(), captures[2].parse().unwrap())
        };

        // We should have gotten `count` elements
        assert_eq!(requests.len(), count);

        // Respond as normal but with a long delay
        ResponseTemplate::new(200).set_delay(Duration::from_secs(365 * 24 * 60 * 60))
    }

    /// Subgraph handler that always fails
    ///
    /// Useful for subgraphs tests that should never actually be called
    fn always_fail(_request: &wiremock::Request) -> ResponseTemplate {
        ResponseTemplate::new(400).set_body_json(serde_json::json!({
            "errors": [{
                "message": "called into subgraph that should not have happened",
            }]
        }))
    }
}