apollo-router 3.0.0-alpha.2

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
//! Implements GraphQL schema introspection.
use std::future::Ready;
use std::num::NonZeroUsize;
use std::sync::Arc;

use futures::future::BoxFuture;
use futures::future::Either;
use sha2::Digest;
use sha2::Sha256;
use tower::BoxError;
use tower::ServiceBuilder;
use tower::ServiceExt as _;
use tower::util::BoxCloneService;

use crate::Configuration;
use crate::cache::storage::CacheStorage;
use crate::compute_job;
use crate::compute_job::ComputeJobType;
use crate::graphql;
use crate::json_ext::Object;
use crate::services::query_parsing::ParsedDocument;
use crate::spec;
use crate::spec::QueryHash;

const DEFAULT_INTROSPECTION_CACHE_CAPACITY: NonZeroUsize = NonZeroUsize::new(5).unwrap();

/// Request type for [IntrospectionService].
pub(crate) struct IntrospectionRequest {
    /// The GraphQL schema to introspect.
    pub(crate) schema: Arc<spec::Schema>,
    /// Document representing the introspection operation to execute.
    pub(crate) document: ParsedDocument,
    /// JSON variable values used to execute the query.
    pub(crate) variables: Object,
}

/// In-memory cache storage for introspection.
pub(crate) type IntrospectionCache = Arc<CacheStorage<IntrospectionCacheKey, graphql::Response>>;

/// A terminal service that handles (partial) execution of introspection.
pub(crate) type IntrospectionService =
    BoxCloneService<IntrospectionRequest, graphql::Response, BoxError>;

#[derive(Clone)]
enum Mode {
    Disabled,
    Enabled {
        storage: IntrospectionCache,
        max_depth: MaxDepth,
    },
}

#[derive(Copy, Clone)]
enum MaxDepth {
    Check,
    Ignore,
}

/// Determine the introspection mode based on YAML configuration.
fn introspection_mode(configuration: &Configuration) -> Mode {
    if configuration.supergraph.introspection {
        let storage = Arc::new(CacheStorage::new_in_memory(
            DEFAULT_INTROSPECTION_CACHE_CAPACITY,
            "introspection",
        ));
        Mode::Enabled {
            storage,
            max_depth: if configuration.limits.router.introspection_max_depth {
                MaxDepth::Check
            } else {
                MaxDepth::Ignore
            },
        }
    } else {
        Mode::Disabled
    }
}

/// Returns a terminal service that does cached, partial execution of introspection.
///
/// If introspection is disabled in config, always returns an error response.
/// If a query contains both introspection and concrete fields, returns an error response.
///
/// Returns the cache object separately for telemetry activation.
pub(crate) fn introspection_service(
    configuration: &Configuration,
) -> (IntrospectionService, Option<IntrospectionCache>) {
    let builder = ServiceBuilder::new()
        .load_shed()
        .layer(RejectMixedIntrospectionLayer::new());

    match introspection_mode(configuration) {
        Mode::Enabled { storage, max_depth } => (
            builder
                .layer(IntrospectionCacheLayer::new(storage.clone()))
                .service(IntrospectionExecutionService::new(max_depth))
                .boxed_clone(),
            Some(storage),
        ),
        Mode::Disabled => (
            builder
                .service(IntrospectionDisabledService::new())
                .boxed_clone(),
            None,
        ),
    }
}

/// Returns if the document contains an introspection query. If this function returns true, it is
/// appropriate to use the introspection service to resolve the query.
///
/// That is:
/// - The operation is a query operation, AND:
/// - The operation has schema introspection fields (__schema or __type)
///
/// Notably, { __typename } is not considered an introspection query.
pub(crate) fn is_introspection_query(document: &ParsedDocument) -> bool {
    let operation = &document.operation;

    operation.is_query()
        && operation
            .root_fields(&document.executable)
            .any(|field| matches!(field.name.as_str(), "__schema" | "__type"))
}

/// Terminal service for GraphQL introspection queries that always returns an error saying
/// introspection is disabled.
#[derive(Clone)]
struct IntrospectionDisabledService {
    _private: (),
}

impl IntrospectionDisabledService {
    fn new() -> Self {
        Self { _private: () }
    }
}

impl tower::Service<IntrospectionRequest> for IntrospectionDisabledService {
    // Actually Infallible, but this matches the IntrospectionExecutionService.
    type Error = BoxError;
    type Response = graphql::Response;
    type Future = Ready<Result<Self::Response, Self::Error>>;

    fn poll_ready(
        &mut self,
        _cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        std::task::Poll::Ready(Ok(()))
    }

    fn call(&mut self, _req: IntrospectionRequest) -> Self::Future {
        let error = graphql::Error::builder()
            .message(String::from("introspection has been disabled"))
            .extension_code("INTROSPECTION_DISABLED")
            .build();
        std::future::ready(Ok(graphql::Response::builder().error(error).build()))
    }
}

/// Short-circuits requests that contain both introspection and concrete fields, responding with GraphQL errors.
struct RejectMixedIntrospectionLayer {
    _private: (),
}
impl RejectMixedIntrospectionLayer {
    fn new() -> Self {
        Self { _private: () }
    }
}

impl<S> tower::Layer<S> for RejectMixedIntrospectionLayer {
    type Service = RejectMixedIntrospectionService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        RejectMixedIntrospectionService { inner }
    }
}

/// Short-circuits requests that contain both introspection and concrete fields, responding with GraphQL errors.
#[derive(Clone)]
struct RejectMixedIntrospectionService<S> {
    inner: S,
}

impl<S> tower::Service<IntrospectionRequest> for RejectMixedIntrospectionService<S>
where
    S: tower::Service<IntrospectionRequest, Response = graphql::Response>,
{
    type Response = graphql::Response;
    type Error = S::Error;
    type Future = Either<
        S::Future,
        // Rejection
        Ready<Result<Self::Response, Self::Error>>,
    >;

    fn poll_ready(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, req: IntrospectionRequest) -> Self::Future {
        let operation = &req.document.operation;

        // We should only receive an IntrospectionRequest if the operation was already determined to
        // contain introspection fields. So, we only have to check if it contains any
        // _non-introspection_ fields to decide if it's a mixed operation.
        if operation
            .root_fields(&req.document.executable)
            .any(|field| !matches!(field.name.as_str(), "__typename" | "__schema" | "__type"))
        {
            let error = graphql::Error::builder()
                .message(
                    "\
                    Mixed queries with both schema introspection and concrete fields \
                    are not supported yet: https://github.com/apollographql/router/issues/2789\
                ",
                )
                .extension_code("MIXED_INTROSPECTION")
                .build();
            Either::Right(std::future::ready(Ok(graphql::Response::builder()
                .error(error)
                .build())))
        } else {
            Either::Left(self.inner.call(req))
        }
    }
}

#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub(crate) struct IntrospectionCacheKey {
    /// Hash of the GraphQL query against a specific schema.
    operation: Arc<QueryHash>,
    /// Hash of the variables used to execute the introspection query.
    variables: sha2::digest::Output<Sha256>,
}

impl std::fmt::Display for IntrospectionCacheKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "introspect:{}:variables:{:x}",
            self.operation, self.variables
        )
    }
}

/// In-memory caching service for introspection requests.
///
/// A stopgap solution until Apollo Platform provides apollo-cache-memory!
#[derive(Clone)]
struct IntrospectionCacheService<S> {
    inner: S,
    cache: IntrospectionCache,
}

/// In-memory caching layer for introspection requests. It uses a fixed cache size.
impl<S> IntrospectionCacheService<S> {
    fn new(inner: S, cache: IntrospectionCache) -> Self {
        Self { inner, cache }
    }
}

/// A stopgap solution until Apollo Platform provides apollo-cache-memory!
struct IntrospectionCacheLayer {
    cache: IntrospectionCache,
}

impl IntrospectionCacheLayer {
    fn new(cache: IntrospectionCache) -> Self {
        Self { cache }
    }
}

impl<S> tower::Layer<S> for IntrospectionCacheLayer {
    type Service = IntrospectionCacheService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        IntrospectionCacheService::new(inner, self.cache.clone())
    }
}

impl<S> tower::Service<IntrospectionRequest> for IntrospectionCacheService<S>
where
    S: tower::Service<IntrospectionRequest, Response = graphql::Response> + Clone + Send + 'static,
    S::Error: Send,
    S::Future: Send + 'static,
{
    type Response = graphql::Response;
    type Error = S::Error;
    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;

    fn poll_ready(
        &mut self,
        _cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        // This should indicate _cache_ readiness--we don't have that concept right now though.
        // We might not use the inner service so we ready it only on cache misses.
        std::task::Poll::Ready(Ok(()))
    }

    fn call(&mut self, req: IntrospectionRequest) -> Self::Future {
        let mut inner = self.inner.clone();
        let cache = self.cache.clone();

        Box::pin(async move {
            let cache_key = if let Ok(variable_key) = serde_json::to_string(&req.variables) {
                let mut hasher = Sha256::new();
                hasher.update(variable_key);
                IntrospectionCacheKey {
                    operation: req.document.hash.clone(),
                    variables: hasher.finalize(),
                }
            } else {
                tracing::warn!(
                    "Failed to serialize variables for introspection cache key, skipping cache: {:?}",
                    req.variables
                );

                return inner.ready().await?.call(req).await;
            };

            if let Some(response) = cache.get(&cache_key, |_| unreachable!()).await {
                return Ok(response);
            }

            let response = inner.ready().await?.call(req).await?;
            cache.insert(cache_key, response.clone()).await;

            Ok(response)
        })
    }
}

/// Terminal service for executing GraphQL introspection queries against a schema.
///
/// Only the introspection parts of the input GraphQL query are executed. Non-introspection parts
/// are silently ignored.
///
/// When the introspection depth limit is exceeded, returns an error response.
#[derive(Clone)]
struct IntrospectionExecutionService {
    max_depth: MaxDepth,
}

impl IntrospectionExecutionService {
    fn new(max_depth: MaxDepth) -> Self {
        Self { max_depth }
    }
}

impl tower::Service<IntrospectionRequest> for IntrospectionExecutionService {
    type Response = graphql::Response;
    type Error = BoxError;
    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;

    fn poll_ready(
        &mut self,
        _cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        std::task::Poll::Ready(Ok(()))
    }

    fn call(&mut self, req: IntrospectionRequest) -> Self::Future {
        let max_depth = self.max_depth;

        Box::pin(async move {
            Ok(
                compute_job::execute(ComputeJobType::Introspection, move |_| {
                    execute_introspection(max_depth, &req.schema, &req.document, req.variables)
                })?
                .await,
            )
        })
    }
}

fn execute_introspection(
    max_depth: MaxDepth,
    schema: &spec::Schema,
    doc: &ParsedDocument,
    variables: Object,
) -> graphql::Response {
    let api_schema = schema.api_schema();
    let operation = &doc.operation;
    let max_depth_result = match max_depth {
        MaxDepth::Check => {
            apollo_compiler::introspection::check_max_depth(&doc.executable, operation)
        }
        MaxDepth::Ignore => Ok(()),
    };
    let result = max_depth_result
        .and_then(|()| {
            apollo_compiler::request::coerce_variable_values(api_schema, operation, &variables)
        })
        .and_then(|variable_values| {
            apollo_compiler::introspection::partial_execute(
                api_schema,
                &schema.implementers_map,
                &doc.executable,
                operation,
                &variable_values,
            )
        });
    match result {
        Ok(response) => response.into(),
        Err(e) => {
            let error = e.to_graphql_error(&doc.executable.sources);
            graphql::Response::builder().error(error).build()
        }
    }
}

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

    use tower::Service as _;
    use tower::ServiceBuilder;
    use tower::ServiceExt as _;

    use super::IntrospectionCacheLayer;
    use super::IntrospectionRequest;
    use super::RejectMixedIntrospectionLayer;
    use super::introspection_service;
    use crate::Configuration;
    use crate::cache::storage::CacheStorage;
    use crate::graphql;
    use crate::spec::Query;
    use crate::spec::Schema;

    #[tokio::test]
    async fn introspection_cache_hit() {
        let (mock, mut handle) =
            tower_test::mock::pair::<IntrospectionRequest, graphql::Response>();
        let driver = tokio::task::spawn(async move {
            let (_request, responder) = handle.next_request().await.unwrap();
            responder.send_response(
                graphql::Response::builder()
                    .data(serde_json_bytes::json!({
                        "__schema": {
                            "queryType": {
                                "name": "Query",
                            },
                        },
                    }))
                    .build(),
            );
        });

        let config = Configuration::default();
        let schema =
            Arc::new(Schema::parse(include_str!("testdata/supergraph.graphql"), &config).unwrap());
        let query = "{ __schema { queryType { name } } }";

        let cache = Arc::new(CacheStorage::new_in_memory(
            NonZeroUsize::new(5).unwrap(),
            "introspection",
        ));
        let mut service = ServiceBuilder::new()
            .layer(IntrospectionCacheLayer::new(cache))
            .service(mock);

        // We should be able to call the mock service twice with the same query, despite only handling
        // one request.

        let document = Query::parse_document(query, None, &schema, &config).unwrap();
        service
            .ready()
            .await
            .unwrap()
            .call(IntrospectionRequest {
                schema: schema.clone(),
                document,
                variables: Default::default(),
            })
            .await
            .unwrap();

        let document = Query::parse_document(query, None, &schema, &config).unwrap();
        service
            .ready()
            .await
            .unwrap()
            .call(IntrospectionRequest {
                schema: schema.clone(),
                document,
                variables: Default::default(),
            })
            .await
            .unwrap();

        drop(service);
        crate::plugin::test::await_mock_driver(driver).await;
    }

    #[tokio::test]
    async fn test_reject_mixed_introspection() {
        let (mock, mut handle) =
            tower_test::mock::pair::<IntrospectionRequest, graphql::Response>();

        // We expect one introspection request to go through, and the mixed request not to reach the
        // inner service.
        let driver = tokio::task::spawn(async move {
            let (_request, responder) = handle.next_request().await.unwrap();
            responder.send_response(
                graphql::Response::builder()
                    .data(serde_json_bytes::json!({
                        "__schema": {
                            "queryType": {
                                "name": "Query",
                            },
                        },
                    }))
                    .build(),
            );
        });

        let config = Configuration::default();
        let schema =
            Arc::new(Schema::parse(include_str!("testdata/supergraph.graphql"), &config).unwrap());

        let introspection_query = r#"{ __schema { queryType { name } } }"#;
        let introspection_document =
            Query::parse_document(introspection_query, None, &schema, &config).unwrap();

        let mixed_query = r#"{
            __schema { queryType { name } }
            me { id }
        }"#;
        let mixed_document = Query::parse_document(mixed_query, None, &schema, &config).unwrap();

        let mut service = ServiceBuilder::new()
            .layer(RejectMixedIntrospectionLayer::new())
            .service(mock);

        let mixed_response = service
            .ready()
            .await
            .unwrap()
            .call(IntrospectionRequest {
                schema: schema.clone(),
                document: mixed_document,
                variables: Default::default(),
            })
            .await
            .unwrap();
        assert!(mixed_response.contains_error_code("MIXED_INTROSPECTION"));

        let introspection_response = service
            .ready()
            .await
            .unwrap()
            .call(IntrospectionRequest {
                schema,
                document: introspection_document,
                variables: Default::default(),
            })
            .await
            .unwrap();
        assert!(introspection_response.errors.is_empty());

        crate::plugin::test::await_mock_driver(driver).await;
    }

    #[tokio::test]
    async fn test_single_aliased_root_typename() {
        let mut config = Configuration::default();
        config.supergraph.introspection = true;
        let schema =
            Arc::new(Schema::parse(include_str!("testdata/supergraph.graphql"), &config).unwrap());
        let query = "{ x: __typename }";
        let document = Query::parse_document(query, None, &schema, &config).unwrap();

        let (service, _cache) = introspection_service(&config);
        let response = service
            .oneshot(IntrospectionRequest {
                schema,
                document,
                variables: Default::default(),
            })
            .await
            .unwrap();

        assert_eq!(
            response.data,
            Some(serde_json_bytes::json!({
                "x": "Query",
            })),
        );
    }

    #[tokio::test]
    async fn test_two_root_typenames() {
        let mut config = Configuration::default();
        config.supergraph.introspection = true;

        let schema =
            Arc::new(Schema::parse(include_str!("testdata/supergraph.graphql"), &config).unwrap());
        let query = "{ x: __typename __typename }";
        let document = Query::parse_document(query, None, &schema, &config).unwrap();

        let (service, _cache) = introspection_service(&config);
        let response = service
            .oneshot(IntrospectionRequest {
                schema,
                document,
                variables: Default::default(),
            })
            .await
            .unwrap();

        assert_eq!(
            response.data,
            Some(serde_json_bytes::json!({
                "x": "Query",
                "__typename": "Query",
            })),
        );
    }
}