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
//! Rhai module tests.

use std::str::FromStr;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::SystemTime;

use http::HeaderMap;
use http::HeaderValue;
use http::Method;
use http::StatusCode;
use rhai::Engine;
use rhai::EvalAltResult;
use serde_json::Value;
use sha2::Digest;
use tower::BoxError;
use tower::Service;
use tower::ServiceExt;
use tower::util::BoxService;
use uuid::Uuid;

use super::PathBuf;
use super::Rhai;
use super::process_error;
use super::subgraph;
use crate::Context;
use crate::graphql;
use crate::graphql::Error;
use crate::graphql::Request;
use crate::http_ext;
use crate::plugin::DynPlugin;
use crate::plugin::test::MockExecutionService;
use crate::plugin::test::MockSupergraphService;
use crate::plugins::rhai::engine::RhaiExecutionDeferredResponse;
use crate::plugins::rhai::engine::RhaiExecutionResponse;
use crate::plugins::rhai::engine::RhaiRouterChunkedResponse;
use crate::plugins::rhai::engine::RhaiRouterFirstRequest;
use crate::plugins::rhai::engine::RhaiRouterResponse;
use crate::plugins::rhai::engine::RhaiSupergraphDeferredResponse;
use crate::plugins::rhai::engine::RhaiSupergraphResponse;
use crate::services::ExecutionRequest;
use crate::services::SubgraphRequest;
use crate::services::SupergraphRequest;
use crate::services::SupergraphResponse;

// There is a lot of repetition in these tests, so I've tried to reduce that with these two
// functions. The repetition could probably be reduced further, but ...
async fn call_rhai_function(fn_name: &str) -> Result<(), Box<rhai::EvalAltResult>> {
    let dyn_plugin: Box<dyn DynPlugin> = crate::plugin::plugins()
        .find(|factory| factory.name == "apollo.rhai")
        .expect("Plugin not found")
        .create_instance_without_schema(
            &Value::from_str(
                r#"{"scripts":"tests/fixtures", "main":"request_response_test.rhai"}"#,
            )
            .unwrap(),
        )
        .await
        .unwrap();

    // Downcast our generic plugin. We know it must be Rhai
    let it: &dyn std::any::Any = dyn_plugin.as_any();
    let rhai_instance: &Rhai = it.downcast_ref::<Rhai>().expect("downcast");

    let block = rhai_instance.block.load();

    // Get a scope to use for our test
    let scope = block.scope.clone();

    let mut guard = scope.lock().unwrap();

    // We must wrap our canned response in Arc<Mutex<Option<>>> to keep the rhai runtime
    // happy
    let response = Arc::new(Mutex::new(Some(subgraph::Response::fake_builder().build())));

    // Call our rhai test function. If it doesn't return an error, the test failed.
    block
        .engine
        .call_fn(&mut guard, &block.ast, fn_name, (response,))
}

async fn call_rhai_function_with_arg<T: Sync + Send + 'static>(
    fn_name: &str,
    arg: T,
) -> Result<(), Box<rhai::EvalAltResult>> {
    let dyn_plugin: Box<dyn DynPlugin> = crate::plugin::plugins()
        .find(|factory| factory.name == "apollo.rhai")
        .expect("Plugin not found")
        .create_instance_without_schema(
            &Value::from_str(
                r#"{"scripts":"tests/fixtures", "main":"request_response_test.rhai"}"#,
            )
            .unwrap(),
        )
        .await
        .unwrap();

    // Downcast our generic plugin. We know it must be Rhai
    let it: &dyn std::any::Any = dyn_plugin.as_any();
    let rhai_instance: &Rhai = it.downcast_ref::<Rhai>().expect("downcast");

    let block = rhai_instance.block.load();

    // Get a scope to use for our test
    let scope = block.scope.clone();

    let mut guard = scope.lock().unwrap();

    // We must wrap our canned request in Arc<Mutex<Option<>>> to keep the rhai runtime
    // happy
    let wrapped_arg = Arc::new(Mutex::new(Some(arg)));

    block
        .engine
        .call_fn(&mut guard, &block.ast, fn_name, (wrapped_arg,))
}

#[tokio::test]
async fn rhai_plugin_supergraph_service() -> Result<(), BoxError> {
    let mut mock_service = MockSupergraphService::new();
    mock_service
        .expect_call()
        .times(1)
        .returning(move |req: SupergraphRequest| {
            Ok(SupergraphResponse::fake_builder()
                .header("x-custom-header", "CUSTOM_VALUE")
                .context(req.context)
                .build()
                .unwrap())
        });

    let dyn_plugin: Box<dyn DynPlugin> = crate::plugin::plugins()
        .find(|factory| factory.name == "apollo.rhai")
        .expect("Plugin not found")
        .create_instance_without_schema(
            &Value::from_str(r#"{"scripts":"tests/fixtures", "main":"test.rhai"}"#).unwrap(),
        )
        .await
        .unwrap();
    let mut router_service = dyn_plugin.supergraph_service(BoxService::new(mock_service));
    let context = Context::new();
    context.insert("test", 5i64).unwrap();
    let supergraph_req = SupergraphRequest::fake_builder().context(context).build()?;

    let mut supergraph_resp = router_service.ready().await?.call(supergraph_req).await?;
    assert_eq!(supergraph_resp.response.status(), 200);
    let headers = supergraph_resp.response.headers().clone();
    let context = supergraph_resp.context.clone();
    // Check if it fails
    let resp = supergraph_resp.next_response().await.unwrap();
    if !resp.errors.is_empty() {
        panic!(
            "Contains errors : {}",
            resp.errors
                .into_iter()
                .map(|err| err.to_string())
                .collect::<Vec<String>>()
                .join("\n")
        );
    }

    assert_eq!(headers.get("coucou").unwrap(), &"hello");
    assert_eq!(headers.get("coming_from_entries").unwrap(), &"value_15");
    assert_eq!(context.get::<_, i64>("test").unwrap().unwrap(), 42i64);
    assert_eq!(
        context.get::<_, String>("addition").unwrap().unwrap(),
        "Here is a new element in the context".to_string()
    );
    Ok(())
}

#[tokio::test]
async fn rhai_plugin_execution_service_error() -> Result<(), BoxError> {
    let mut mock_service = MockExecutionService::new();
    mock_service.expect_clone().return_once(move || {
        let mut mock_service = MockExecutionService::new();
        // The execution_service in test.rhai throws an exception, so we never
        // get a call into the mock service...
        mock_service.expect_call().never();
        mock_service
    });

    let dyn_plugin: Box<dyn DynPlugin> = crate::plugin::plugins()
        .find(|factory| factory.name == "apollo.rhai")
        .expect("Plugin not found")
        .create_instance_without_schema(
            &Value::from_str(r#"{"scripts":"tests/fixtures", "main":"test.rhai"}"#).unwrap(),
        )
        .await
        .unwrap();
    let mut router_service = dyn_plugin.execution_service(BoxService::new(mock_service));
    let fake_req = http_ext::Request::fake_builder()
        .header("x-custom-header", "CUSTOM_VALUE")
        .body(Request::builder().query(String::new()).build())
        .build()?;
    let context = Context::new();
    context.insert("test", 5i64).unwrap();
    let exec_req = ExecutionRequest::fake_builder()
        .context(context)
        .supergraph_request(fake_req)
        .build();

    let mut exec_resp = router_service
        .ready()
        .await
        .unwrap()
        .call(exec_req)
        .await
        .unwrap();
    assert_eq!(
        exec_resp.response.status(),
        http::StatusCode::INTERNAL_SERVER_ERROR
    );
    // Check if it fails
    let body = exec_resp.next_response().await.unwrap();
    if body.errors.is_empty() {
        panic!(
            "Must contain errors : {}",
            body.errors
                .into_iter()
                .map(|err| err.to_string())
                .collect::<Vec<String>>()
                .join("\n")
        );
    }

    assert_eq!(
        body.errors.first().unwrap().message.as_str(),
        "rhai execution error: 'Runtime error: An error occured (line 30, position 5)'"
    );
    Ok(())
}

// A Rhai engine suitable for minimal testing. There are no scripts and the SDL is an empty
// string.
fn new_rhai_test_engine() -> Engine {
    Rhai::new_rhai_engine(None, "".to_string(), PathBuf::new())
}

// Some of these tests rely extensively on internal implementation details of the tracing_test crate.
// These are unstable, so these test may break if the tracing_test crate is updated.
//
// This is done to avoid using the public interface of tracing_test which installs a global
// subscriber which breaks other tests in our stack which also insert a global subscriber.
// (there can be only one...) which means we cannot test it with #[tokio::test(flavor = "multi_thread")]
#[test]
fn it_logs_messages() {
    let env_filter = "apollo_router=trace";
    let mock_writer = tracing_test::internal::MockWriter::new(tracing_test::internal::global_buf());
    let subscriber = tracing_test::internal::get_subscriber(mock_writer, env_filter);

    let _guard = tracing::dispatcher::set_default(&subscriber);
    let engine = new_rhai_test_engine();
    let input_logs = vec![
        r#"log_trace("trace log")"#,
        r#"log_debug("debug log")"#,
        r#"log_info("info log")"#,
        r#"log_warn("warn log")"#,
        r#"log_error("error log")"#,
    ];
    for log in input_logs {
        engine.eval::<()>(log).expect("it logged a message");
    }
    assert!(tracing_test::internal::logs_with_scope_contain(
        "apollo_router",
        "trace log"
    ));
    assert!(tracing_test::internal::logs_with_scope_contain(
        "apollo_router",
        "debug log"
    ));
    assert!(tracing_test::internal::logs_with_scope_contain(
        "apollo_router",
        "info log"
    ));
    assert!(tracing_test::internal::logs_with_scope_contain(
        "apollo_router",
        "warn log"
    ));
    assert!(tracing_test::internal::logs_with_scope_contain(
        "apollo_router",
        "error log"
    ));
}

#[test]
fn it_prints_messages_to_log() {
    use tracing::subscriber;

    use crate::assert_snapshot_subscriber;

    subscriber::with_default(assert_snapshot_subscriber!(), || {
        let engine = new_rhai_test_engine();
        engine
            .eval::<()>(r#"print("info log")"#)
            .expect("it logged a message");
    });
}

#[tokio::test]
async fn it_can_access_sdl_constant() {
    let dyn_plugin: Box<dyn DynPlugin> = crate::plugin::plugins()
        .find(|factory| factory.name == "apollo.rhai")
        .expect("Plugin not found")
        .create_instance_without_schema(
            &Value::from_str(r#"{"scripts":"tests/fixtures", "main":"test.rhai"}"#).unwrap(),
        )
        .await
        .unwrap();

    // Downcast our generic plugin. We know it must be Rhai
    let it: &dyn std::any::Any = dyn_plugin.as_any();
    let rhai_instance: &Rhai = it.downcast_ref::<Rhai>().expect("downcast");

    let block = rhai_instance.block.load();

    // Get a scope to use for our test
    let scope = block.scope.clone();

    let mut guard = scope.lock().unwrap();

    // Call our function to make sure we can access the sdl
    let sdl: String = block
        .engine
        .call_fn(&mut guard, &block.ast, "get_sdl", ())
        .expect("can get sdl");
    assert_eq!(sdl.as_str(), "");
}

#[test]
fn it_provides_helpful_headermap_errors() {
    let mut engine = new_rhai_test_engine();
    engine.register_fn("new_hm", HeaderMap::new);

    let result = engine.eval::<HeaderMap>(
        r#"
let map = new_hm();
map["ümlaut"] = "will fail";
map
"#,
    );
    assert!(result.is_err());
    assert!(matches!(
        *result.unwrap_err(),
        EvalAltResult::ErrorRuntime(..)
    ));
}

#[tokio::test]
async fn it_can_process_router_request() {
    let mut request = RhaiRouterFirstRequest::default();
    request.request.headers_mut().insert(
        "content-type",
        HeaderValue::from_str("application/json").unwrap(),
    );
    *request.request.method_mut() = http::Method::GET;

    call_rhai_function_with_arg("process_router_request", request)
        .await
        .expect("test failed");
}

#[tokio::test]
async fn it_can_process_supergraph_request() {
    let request = SupergraphRequest::canned_builder()
        .operation_name("canned")
        .build()
        .expect("build canned supergraph request");

    call_rhai_function_with_arg("process_supergraph_request", request)
        .await
        .expect("test failed");
}

#[tokio::test]
async fn it_can_process_execution_request() {
    let request = ExecutionRequest::fake_builder().build();
    call_rhai_function_with_arg("process_execution_request", request)
        .await
        .expect("test failed");
}

#[tokio::test]
async fn it_can_process_subgraph_request() {
    let request = SubgraphRequest::fake_builder().build();
    call_rhai_function_with_arg("process_subgraph_request", request)
        .await
        .expect("test failed");
}

#[tokio::test]
async fn it_can_process_router_response() {
    let response = RhaiRouterResponse::default();
    call_rhai_function_with_arg("process_router_response", response)
        .await
        .expect("test failed");
}

#[tokio::test]
async fn it_can_process_router_chunked_response() {
    let response = RhaiRouterChunkedResponse::default();
    call_rhai_function_with_arg("process_router_chunked_response", response)
        .await
        .expect("test failed");
}

#[tokio::test]
async fn it_can_process_supergraph_response() {
    let response = RhaiSupergraphResponse::default();
    call_rhai_function_with_arg("process_supergraph_response", response)
        .await
        .expect("test failed");
}

#[tokio::test]
async fn it_can_process_supergraph_deferred_response() {
    let response = RhaiSupergraphDeferredResponse::default();
    call_rhai_function_with_arg("process_supergraph_deferred_response", response)
        .await
        .expect("test failed");
}

#[tokio::test]
async fn it_can_process_execution_response() {
    let response = RhaiExecutionResponse::default();
    call_rhai_function_with_arg("process_execution_response", response)
        .await
        .expect("test failed");
}

#[tokio::test]
async fn it_can_process_execution_deferred_response() {
    let response = RhaiExecutionDeferredResponse::default();
    call_rhai_function_with_arg("process_execution_deferred_response", response)
        .await
        .expect("test failed");
}

#[tokio::test]
async fn it_can_process_subgraph_response() {
    let response = subgraph::Response::fake_builder()
        .status_code(StatusCode::OK)
        .build();
    call_rhai_function_with_arg("process_subgraph_response", response)
        .await
        .expect("test failed");
}

#[tokio::test]
async fn it_can_parse_request_uri() {
    let mut request = SupergraphRequest::canned_builder()
        .operation_name("canned")
        .build()
        .expect("build canned supergraph request");
    *request.supergraph_request.uri_mut() = "https://not-default:8080/path".parse().unwrap();
    call_rhai_function_with_arg("test_parse_request_details", request)
        .await
        .expect("test failed");
}

#[test]
fn it_can_urlencode_string() {
    let engine = new_rhai_test_engine();
    let encoded: String = engine
        .eval(r#"urlencode("This has an ümlaut in it.")"#)
        .expect("can encode string");
    assert_eq!(encoded, "This%20has%20an%20%C3%BCmlaut%20in%20it.");
}

#[test]
fn it_can_urldecode_string() {
    let engine = new_rhai_test_engine();
    let decoded: String = engine
        .eval(r#"urldecode("This%20has%20an%20%C3%BCmlaut%20in%20it.")"#)
        .expect("can decode string");
    assert_eq!(decoded, "This has an ümlaut in it.");
}

#[test]
fn it_can_base64encode_string() {
    let engine = new_rhai_test_engine();
    let encoded: String = engine
        .eval(r#"base64::encode("This has an ümlaut in it.")"#)
        .expect("can encode string");
    assert_eq!(encoded, "VGhpcyBoYXMgYW4gw7xtbGF1dCBpbiBpdC4=");
}

#[test]
fn it_can_base64decode_string() {
    let engine = new_rhai_test_engine();
    let decoded: String = engine
        .eval(r#"base64::decode("VGhpcyBoYXMgYW4gw7xtbGF1dCBpbiBpdC4=")"#)
        .expect("can decode string");
    assert_eq!(decoded, "This has an ümlaut in it.");
}

#[test]
fn it_can_base64encode_string_with_alphabet() {
    let engine = new_rhai_test_engine();
    let encoded: String = engine
        .eval(r#"base64::encode("<<???>>", base64::STANDARD)"#)
        .expect("can encode string");
    assert_eq!(encoded, "PDw/Pz8+Pg==");
    let encoded: String = engine
        .eval(r#"base64::encode("<<???>>", base64::URL_SAFE)"#)
        .expect("can encode string");
    assert_eq!(encoded, "PDw_Pz8-Pg==");
}

#[test]
fn it_can_base64decode_string_with_alphabet() {
    let engine = new_rhai_test_engine();
    let decoded: String = engine
        .eval(r#"base64::decode("PDw/Pz8+Pg==", base64::STANDARD)"#)
        .expect("can decode string");
    assert_eq!(decoded, "<<???>>");
    let decoded: String = engine
        .eval(r#"base64::decode("PDw_Pz8-Pg==", base64::URL_SAFE)"#)
        .expect("can decode string");
    assert_eq!(decoded, "<<???>>");
}

#[test]
fn it_can_create_unix_now() {
    let engine = new_rhai_test_engine();
    let st = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .expect("can get system time")
        .as_secs() as i64;
    let unix_now: i64 = engine
        .eval(r#"unix_now()"#)
        .expect("can get unix_now() timestamp");
    // Always difficult to do timing tests. unix_now() should execute within a second of st,
    // so...
    assert!(st <= unix_now && unix_now <= st + 1);
}

#[test]
fn it_can_create_unix_ms_now() {
    let engine = new_rhai_test_engine();
    let st = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .expect("can get system time")
        .as_millis() as i64;
    let unix_ms_now: i64 = engine
        .eval(r#"unix_ms_now()"#)
        .expect("can get unix_ms_now() timestamp");
    // Always difficult to do timing tests. unix_ms_now() should execute within a second of st,
    // so...
    assert!(st <= unix_ms_now && unix_ms_now <= st + 1000);
}

#[test]
fn it_can_generate_uuid() {
    let engine = new_rhai_test_engine();
    let uuid_v4_rhai: String = engine.eval(r#"uuid_v4()"#).expect("can get uuid");
    // attempt to parse back to UUID..
    let uuid_parsed = Uuid::parse_str(uuid_v4_rhai.as_str()).expect("can parse uuid from string");
    // finally validate that parsed string equals the returned value
    assert_eq!(uuid_v4_rhai, uuid_parsed.to_string());
}

#[test]
fn it_can_sha256_string() {
    let engine = new_rhai_test_engine();
    let hash = sha2::Sha256::digest("hello world".as_bytes());
    let hash_rhai: String = engine
        .eval(r#"sha256::digest("hello world")"#)
        .expect("can decode string");
    assert_eq!(hash_rhai, hex::encode(hash));
}

async fn base_globals_function(fn_name: &str) -> Result<bool, Box<rhai::EvalAltResult>> {
    let dyn_plugin: Box<dyn DynPlugin> = crate::plugin::plugins()
        .find(|factory| factory.name == "apollo.rhai")
        .expect("Plugin not found")
        .create_instance_without_schema(
            &Value::from_str(
                r#"{"scripts":"tests/fixtures", "main":"global_variables_test.rhai"}"#,
            )
            .unwrap(),
        )
        .await
        .unwrap();

    // Downcast our generic plugin. We know it must be Rhai
    let it: &dyn std::any::Any = dyn_plugin.as_any();
    let rhai_instance: &Rhai = it.downcast_ref::<Rhai>().expect("downcast");

    let block = rhai_instance.block.load();

    // Get a scope to use for our test
    let scope = block.scope.clone();

    let mut guard = scope.lock().unwrap();

    // Call our rhai test function. If it doesn't return an error, the test failed.
    block.engine.call_fn(&mut guard, &block.ast, fn_name, ())
}

#[tokio::test]
async fn it_can_find_router_global_variables() {
    if let Err(error) = base_globals_function("process_router_global_variables").await {
        panic!("test failed: {error:?}");
    }
}

#[tokio::test]
async fn it_can_process_om_subgraph_forbidden() {
    if let Err(error) = call_rhai_function("process_subgraph_response_om_forbidden").await {
        let processed_error = process_error(error);
        assert_eq!(processed_error.status, StatusCode::FORBIDDEN);
        assert_eq!(
            processed_error.message,
            Some("I have raised a 403".to_string())
        );
    } else {
        // Test failed
        panic!("error processed incorrectly");
    }
}

#[tokio::test]
async fn it_can_process_om_subgraph_forbidden_with_graphql_payload() {
    let error = call_rhai_function("process_subgraph_response_om_forbidden_graphql")
        .await
        .unwrap_err();

    let processed_error = process_error(error);
    assert_eq!(processed_error.status, StatusCode::FORBIDDEN);
    assert_eq!(
        processed_error.body,
        Some(
            graphql::Response::builder()
                .errors(vec![{
                    Error::builder()
                        .message("I have raised a 403")
                        .extension_code("ACCESS_DENIED")
                        .build()
                }])
                .build()
        )
    );
}

#[tokio::test]
async fn it_can_process_om_subgraph_200_with_graphql_data() {
    let error = call_rhai_function("process_subgraph_response_om_200_graphql")
        .await
        .unwrap_err();

    let processed_error = process_error(error);
    assert_eq!(processed_error.status, StatusCode::OK);
    assert_eq!(
        processed_error.body,
        Some(
            graphql::Response::builder()
                .data(serde_json::json!({ "name": "Ada Lovelace"}))
                .build()
        )
    );
}

#[tokio::test]
async fn it_can_process_string_subgraph_forbidden() {
    if let Err(error) = call_rhai_function("process_subgraph_response_string").await {
        let processed_error = process_error(error);
        assert_eq!(processed_error.status, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(processed_error.message, Some("rhai execution error: 'Runtime error: I have raised an error (line 251, position 5)'".to_string()));
    } else {
        // Test failed
        panic!("error processed incorrectly");
    }
}

#[tokio::test]
async fn it_can_process_ok_subgraph_forbidden() {
    let error = call_rhai_function("process_subgraph_response_om_ok")
        .await
        .unwrap_err();
    let processed_error = process_error(error);
    assert_eq!(processed_error.status, StatusCode::OK);
    assert_eq!(
        processed_error.message,
        Some("I have raised a 200".to_string())
    );
}

#[tokio::test]
async fn it_cannot_process_om_subgraph_missing_message_and_body() {
    if let Err(error) = call_rhai_function("process_subgraph_response_om_missing_message").await {
        let processed_error = process_error(error);
        assert_eq!(processed_error.status, StatusCode::BAD_REQUEST);
        assert_eq!(
            processed_error.message,
            Some(
                "rhai execution error: 'Runtime error: #{\"status\": 400} (line 262, position 5)'"
                    .to_string()
            )
        );
    } else {
        // Test failed
        panic!("error processed incorrectly");
    }
}

#[tokio::test]
async fn it_mentions_source_when_syntax_error_occurs() {
    let err: Box<dyn std::error::Error> = crate::plugin::plugins()
        .find(|factory| factory.name == "apollo.rhai")
        .expect("Plugin not found")
        .create_instance_without_schema(
            &Value::from_str(r#"{"scripts":"tests/fixtures", "main":"syntax_errors.rhai"}"#)
                .unwrap(),
        )
        .await
        .err()
        .unwrap();

    assert!(err.to_string().contains("syntax_errors.rhai"));
}

#[test]
#[should_panic(
    expected = "can use env: ErrorRuntime(\"could not expand variable: THIS_SHOULD_NOT_EXIST, environment variable not found\", none)"
)]
fn it_cannot_expand_missing_environment_variable() {
    assert!(std::env::var("THIS_SHOULD_NOT_EXIST").is_err());
    let engine = new_rhai_test_engine();
    let _: String = engine
        .eval(
            r#"
        env::get("THIS_SHOULD_NOT_EXIST")"#,
        )
        .expect("can use env");
}

// POSIX specifies HOME is always set
#[test]
fn it_can_expand_environment_variable() {
    let home = std::env::var("HOME").expect("can always read HOME");
    let engine = new_rhai_test_engine();
    let env_variable: String = engine
        .eval(
            r#"
        env::get("HOME")"#,
        )
        .expect("can use env");
    assert_eq!(home, env_variable);
}

#[test]
fn it_can_compare_method_strings() {
    let mut engine = new_rhai_test_engine();
    engine.register_fn(
        "new_method",
        |method: &str| -> Result<Method, Box<EvalAltResult>> {
            Method::from_str(&method.to_uppercase()).map_err(|e| e.to_string().into())
        },
    );

    let method: bool = engine
        .eval(
            r#"
        let get = new_method("GEt").to_string();
        get == "GET"
        "#,
        )
        .expect("can compare properly");
    assert!(method);
}

#[tokio::test]
async fn test_router_service_adds_timestamp_header() -> Result<(), BoxError> {
    let mut mock_service = MockSupergraphService::new();
    mock_service
        .expect_call()
        .times(1)
        .returning(move |req: SupergraphRequest| {
            Ok(SupergraphResponse::fake_builder()
                .header("x-custom-header", "CUSTOM_VALUE")
                .context(req.context)
                .build()
                .unwrap())
        });

    let dyn_plugin: Box<dyn DynPlugin> = crate::plugin::plugins()
        .find(|factory| factory.name == "apollo.rhai")
        .expect("Plugin not found")
        .create_instance_without_schema(
            &Value::from_str(r#"{"scripts":"tests/fixtures", "main":"remove_header.rhai"}"#)
                .unwrap(),
        )
        .await
        .unwrap();

    let mut router_service = dyn_plugin.supergraph_service(BoxService::new(mock_service));
    let context = Context::new();
    context.insert("test", 5i64).unwrap();
    let supergraph_req = SupergraphRequest::fake_builder()
        .header("x-custom-header", "CUSTOM_VALUE")
        .context(context)
        .build()?;

    let service_response = router_service.ready().await?.call(supergraph_req).await?;
    assert_eq!(StatusCode::OK, service_response.response.status());

    let headers = service_response.response.headers().clone();
    assert!(headers.get("x-custom-header").is_none());

    Ok(())
}

#[tokio::test]
async fn it_can_access_demand_control_context() -> Result<(), BoxError> {
    let mut mock_service = MockSupergraphService::new();
    mock_service
        .expect_call()
        .times(1)
        .returning(move |req: SupergraphRequest| {
            Ok(SupergraphResponse::fake_builder()
                .context(req.context)
                .build()
                .unwrap())
        });

    let dyn_plugin: Box<dyn DynPlugin> = crate::plugin::plugins()
        .find(|factory| factory.name == "apollo.rhai")
        .expect("Plugin not found")
        .create_instance_without_schema(
            &Value::from_str(r#"{"scripts":"tests/fixtures", "main":"demand_control.rhai"}"#)
                .unwrap(),
        )
        .await
        .unwrap();

    let mut router_service = dyn_plugin.supergraph_service(BoxService::new(mock_service));
    let context = Context::new();
    context.insert_estimated_cost(50.0).unwrap();
    context.insert_actual_cost(35.0).unwrap();
    context
        .insert_cost_strategy("test_strategy".to_string())
        .unwrap();
    context.insert_cost_result("COST_OK".to_string()).unwrap();
    let supergraph_req = SupergraphRequest::fake_builder().context(context).build()?;

    let service_response = router_service.ready().await?.call(supergraph_req).await?;
    assert_eq!(StatusCode::OK, service_response.response.status());

    let headers = service_response.response.headers().clone();
    let demand_control_header = headers
        .get("demand-control-estimate")
        .map(|h| h.to_str().unwrap());
    assert_eq!(demand_control_header, Some("50.0"));

    let demand_control_header = headers
        .get("demand-control-actual")
        .map(|h| h.to_str().unwrap());
    assert_eq!(demand_control_header, Some("35.0"));

    let demand_control_header = headers
        .get("demand-control-strategy")
        .map(|h| h.to_str().unwrap());
    assert_eq!(demand_control_header, Some("test_strategy"));

    let demand_control_header = headers
        .get("demand-control-result")
        .map(|h| h.to_str().unwrap());
    assert_eq!(demand_control_header, Some("COST_OK"));

    Ok(())
}