apollo-router 2.13.1

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
//!  Persisted query manifest poller. Once created, will poll for updates continuously, reading persisted queries into memory.

use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Arc;

use apollo_compiler::ast;
use futures::prelude::*;
use parking_lot::RwLock;
use reqwest::Client;
use tokio::fs::read_to_string;
use tokio::sync::mpsc;
use tower::BoxError;

use super::freeform_graphql_behavior::FreeformGraphQLAction;
use super::freeform_graphql_behavior::FreeformGraphQLBehavior;
use super::freeform_graphql_behavior::get_freeform_graphql_behavior;
use super::manifest::FullPersistedQueryOperationId;
use super::manifest::PersistedQueryManifest;
use super::manifest::SignedUrlChunk;
use crate::Configuration;
use crate::uplink::UplinkConfig;
use crate::uplink::persisted_queries_manifest_stream::MaybePersistedQueriesManifestChunks;
use crate::uplink::persisted_queries_manifest_stream::PersistedQueriesManifestChunk;
use crate::uplink::persisted_queries_manifest_stream::PersistedQueriesManifestQuery;
use crate::uplink::stream_from_uplink_transforming_new_response;

#[derive(Debug)]
pub(crate) struct PersistedQueryManifestPollerState {
    persisted_query_manifest: PersistedQueryManifest,
    pub(crate) freeform_graphql_behavior: FreeformGraphQLBehavior,
}

/// Manages polling uplink for persisted query chunks and unpacking those chunks into a [`PersistedQueryManifest`].
#[derive(Debug)]
pub(crate) struct PersistedQueryManifestPoller {
    pub(crate) state: Arc<RwLock<PersistedQueryManifestPollerState>>,
    _drop_signal: mpsc::Sender<()>,
}

impl PersistedQueryManifestPoller {
    /// Create a new [`PersistedQueryManifestPoller`] from CLI options and YAML configuration.
    /// Starts polling immediately and this function only returns after all chunks have been fetched
    /// and the [`PersistedQueryManifest`] has been fully populated.
    pub(crate) async fn new(config: Configuration) -> Result<Self, BoxError> {
        let manifest_source = ManifestSource::from_config(&config)?;
        let manifest_stream = create_manifest_stream(manifest_source).await?;

        // Initialize state
        let state = Arc::new(RwLock::new(PersistedQueryManifestPollerState {
            persisted_query_manifest: PersistedQueryManifest::default(),
            freeform_graphql_behavior: FreeformGraphQLBehavior::DenyAll { log_unknown: false },
        }));

        // Start the background polling task
        let (_drop_signal, drop_receiver) = mpsc::channel::<()>(1);
        let (ready_sender, mut ready_receiver) = mpsc::channel::<ManifestPollResultOnStartup>(1);

        let state_clone = state.clone();
        let config_clone = config.clone();

        tokio::task::spawn(async move {
            poll_manifest_stream(
                manifest_stream,
                state_clone,
                config_clone,
                ready_sender,
                drop_receiver,
            )
            .await;
        });

        match ready_receiver.recv().await {
            Some(ManifestPollResultOnStartup::LoadedOperations) => Ok(Self {
                state,
                _drop_signal,
            }),
            Some(ManifestPollResultOnStartup::Err(e)) => Err(e),
            None => Err("could not receive ready event for persisted query layer".into()),
        }
    }

    pub(crate) fn get_operation_body(
        &self,
        persisted_query_id: &str,
        client_name: Option<String>,
    ) -> Option<String> {
        let state = self.state.read();
        if let Some(body) = state
            .persisted_query_manifest
            .get(&FullPersistedQueryOperationId {
                operation_id: persisted_query_id.to_string(),
                client_name: client_name.clone(),
            })
            .cloned()
        {
            Some(body)
        } else if client_name.is_some() {
            state
                .persisted_query_manifest
                .get(&FullPersistedQueryOperationId {
                    operation_id: persisted_query_id.to_string(),
                    client_name: None,
                })
                .cloned()
        } else {
            None
        }
    }

    pub(crate) fn get_all_operations(&self) -> Vec<String> {
        let state = self.state.read();
        state.persisted_query_manifest.values().cloned().collect()
    }

    pub(crate) fn action_for_freeform_graphql(
        &self,
        ast: Result<&ast::Document, &str>,
    ) -> FreeformGraphQLAction {
        let state = self.state.read();
        state
            .freeform_graphql_behavior
            .action_for_freeform_graphql(ast)
    }

    // Some(bool) means "never allows freeform GraphQL, bool is whether or not to log"
    // None means "sometimes allows freeform GraphQL"
    pub(crate) fn never_allows_freeform_graphql(&self) -> Option<bool> {
        let state = self.state.read();
        if let FreeformGraphQLBehavior::DenyAll { log_unknown } = state.freeform_graphql_behavior {
            Some(log_unknown)
        } else {
            None
        }
    }

    // The way we handle requests that contain an unknown ID or which contain
    // both an ID and its body depends on whether or not APQ is also enabled.
    // It's important that we never allow APQ to be enabled when we're running
    // in a safelisting mode; this function ensures that by only ever returning
    // true from non-safelisting modes.
    pub(crate) fn augmenting_apq_with_pre_registration_and_no_safelisting(&self) -> bool {
        let state = self.state.read();
        match state.freeform_graphql_behavior {
            FreeformGraphQLBehavior::AllowAll { apq_enabled, .. }
            | FreeformGraphQLBehavior::LogUnlessInSafelist { apq_enabled, .. } => apq_enabled,
            _ => false,
        }
    }
}

async fn manifest_from_uplink_chunks(
    new_chunks: Vec<PersistedQueriesManifestChunk>,
    http_client: Client,
) -> Result<PersistedQueryManifest, BoxError> {
    let mut new_persisted_query_manifest = PersistedQueryManifest::default();
    tracing::debug!("ingesting new persisted queries: {:?}", &new_chunks);
    // TODO: consider doing these fetches in parallel
    for new_chunk in new_chunks {
        fetch_chunk_into_manifest(
            new_chunk,
            &mut new_persisted_query_manifest,
            http_client.clone(),
        )
        .await?
    }

    tracing::info!(
        "Loaded {} persisted queries.",
        new_persisted_query_manifest.len()
    );

    Ok(new_persisted_query_manifest)
}

async fn fetch_chunk_into_manifest(
    chunk: PersistedQueriesManifestChunk,
    manifest: &mut PersistedQueryManifest,
    http_client: Client,
) -> Result<(), BoxError> {
    let mut it = chunk.urls.iter().peekable();
    while let Some(chunk_url) = it.next() {
        match fetch_chunk(http_client.clone(), chunk_url).await {
            Ok(chunk) => {
                manifest.add_chunk(&chunk);
                return Ok(());
            }
            Err(e) => {
                if it.peek().is_some() {
                    // There's another URL to try, so log as debug and move on.
                    tracing::debug!(
                        "failed to fetch persisted query list chunk from {}: {}. \
                         Other endpoints will be tried",
                        chunk_url,
                        e
                    );
                    continue;
                } else {
                    // No more URLs; fail the function.
                    return Err(e);
                }
            }
        }
    }
    // The loop always returns unless there's another iteration after it, so the
    // only way we can fall off the loop is if we never entered it.
    Err("persisted query chunk did not include any URLs to fetch operations from".into())
}

async fn fetch_chunk(http_client: Client, chunk_url: &String) -> Result<SignedUrlChunk, BoxError> {
    let chunk = http_client
        .get(chunk_url.clone())
        .send()
        .await
        .and_then(|r| r.error_for_status())
        .map_err(|e| -> BoxError {
            format!("error fetching persisted queries manifest chunk from {chunk_url}: {e}").into()
        })?
        .json::<SignedUrlChunk>()
        .await
        .map_err(|e| -> BoxError {
            format!("error reading body of persisted queries manifest chunk from {chunk_url}: {e}")
                .into()
        })?;

    chunk.validate()
}

/// The result of the first time build of the persisted query manifest.
#[derive(Debug)]
pub(crate) enum ManifestPollResultOnStartup {
    LoadedOperations,
    Err(BoxError),
}

/// The source of persisted query manifests
#[derive(Debug)]
enum ManifestSource {
    LocalStatic(Vec<String>),
    LocalHotReload(Vec<String>),
    Uplink(UplinkConfig),
}

impl ManifestSource {
    fn from_config(config: &Configuration) -> Result<Self, BoxError> {
        let source = if config.persisted_queries.hot_reload {
            if let Some(paths) = &config.persisted_queries.local_manifests {
                ManifestSource::LocalHotReload(paths.clone())
            } else {
                return Err("`persisted_queries.hot_reload` requires `local_manifests`".into());
            }
        } else if let Some(paths) = &config.persisted_queries.local_manifests {
            ManifestSource::LocalStatic(paths.clone())
        } else if let Some(uplink_config) = config.uplink.as_ref() {
            ManifestSource::Uplink(uplink_config.clone())
        } else {
            return Err(
                "persisted queries requires either local_manifests or Apollo GraphOS configuration"
                    .into(),
            );
        };

        Ok(source)
    }
}

/// A stream of manifest updates
type ManifestStream = dyn Stream<Item = Result<PersistedQueryManifest, BoxError>> + Send + 'static;

async fn create_manifest_stream(
    source: ManifestSource,
) -> Result<Pin<Box<ManifestStream>>, BoxError> {
    match source {
        ManifestSource::LocalStatic(paths) => Ok(stream::once(load_local_manifests(paths)).boxed()),
        ManifestSource::LocalHotReload(paths) => Ok(create_hot_reload_stream(paths).boxed()),
        ManifestSource::Uplink(uplink_config) => {
            let client = Client::builder()
                .timeout(uplink_config.timeout)
                .gzip(true)
                .build()?;
            Ok(create_uplink_stream(uplink_config, client).boxed())
        }
    }
}

async fn poll_manifest_stream(
    mut manifest_stream: Pin<Box<ManifestStream>>,
    state: Arc<RwLock<PersistedQueryManifestPollerState>>,
    config: Configuration,
    ready_sender: mpsc::Sender<ManifestPollResultOnStartup>,
    mut drop_receiver: mpsc::Receiver<()>,
) {
    let mut ready_sender = Some(ready_sender);

    loop {
        tokio::select! {
            manifest_result = manifest_stream.next() => {
                match manifest_result {
                    Some(Ok(new_manifest)) => {
                        let operation_count = new_manifest.len();
                        let freeform_graphql_behavior =
                            get_freeform_graphql_behavior(&config, &new_manifest);

                        *state.write() = PersistedQueryManifestPollerState {
                            persisted_query_manifest: new_manifest,
                            freeform_graphql_behavior,
                        };
                        tracing::info!("persisted query manifest successfully updated ({} operations total)", operation_count);

                        if let Some(sender) = ready_sender.take() {
                            let _ = sender.send(ManifestPollResultOnStartup::LoadedOperations).await;
                        }
                    }
                    Some(Err(e)) => {
                        if let Some(sender) = ready_sender.take() {
                            let _ = sender.send(ManifestPollResultOnStartup::Err(e)).await;
                        } else {
                            tracing::error!("Error polling manifest: {}", e);
                        }
                    }
                    None => break,
                }
            }
            _ = drop_receiver.recv() => break,
        }
    }
}

async fn load_local_manifests(paths: Vec<String>) -> Result<PersistedQueryManifest, BoxError> {
    let mut complete_manifest = PersistedQueryManifest::default();

    for path in paths.iter() {
        let raw_file_contents = read_to_string(path).await.map_err(|e| -> BoxError {
            format!("Failed to read persisted query list file at path: {path}, {e}").into()
        })?;

        let chunk = SignedUrlChunk::parse_and_validate(&raw_file_contents)?;
        complete_manifest.add_chunk(&chunk);
    }

    tracing::info!(
        "Loaded {} persisted queries from local files.",
        complete_manifest.len()
    );

    Ok(complete_manifest)
}

fn create_uplink_stream(
    uplink_config: UplinkConfig,
    http_client: Client,
) -> impl Stream<Item = Result<PersistedQueryManifest, BoxError>> {
    stream_from_uplink_transforming_new_response::<
        PersistedQueriesManifestQuery,
        MaybePersistedQueriesManifestChunks,
        Option<PersistedQueryManifest>,
    >(uplink_config, move |response| {
        let http_client = http_client.clone();
        Box::new(Box::pin(async move {
            match response {
                Some(chunks) => manifest_from_uplink_chunks(chunks, http_client)
                    .await
                    .map(Some)
                    .map_err(|e| -> BoxError { e }),
                None => Ok(None),
            }
        }))
    })
    .filter_map(|result| async move {
        match result {
            Ok(Some(manifest)) => Some(Ok(manifest)),
            Ok(None) => Some(Ok(PersistedQueryManifest::default())),
            Err(e) => Some(Err(e.into())),
        }
    })
}

fn create_hot_reload_stream(
    paths: Vec<String>,
) -> impl Stream<Item = Result<PersistedQueryManifest, BoxError>> {
    // Create file watchers for each path
    let file_watchers = paths.into_iter().map(|raw_path| {
        crate::files::watch(std::path::Path::new(&raw_path.clone())).then(move |_| {
            let raw_path = raw_path.clone();
            async move {
                match read_to_string(&raw_path).await {
                    Ok(raw_file_contents) => {
                        match SignedUrlChunk::parse_and_validate(&raw_file_contents) {
                            Ok(chunk) => Ok((raw_path, chunk)),
                            Err(e) => Err(e),
                        }
                    }
                    Err(e) => Err(e.into()),
                }
            }
            .boxed()
        })
    });

    // We need to keep track of the local manifest chunks so we can replace them when
    // they change.
    let mut chunks: HashMap<String, SignedUrlChunk> = HashMap::new();

    // Combine all watchers into a single stream
    stream::select_all(file_watchers).map(move |result| {
        result.map(|(path, chunk)| {
            tracing::info!(
                "hot reloading persisted query manifest file at path: {}",
                path
            );
            chunks.insert(path, chunk);

            let mut manifest = PersistedQueryManifest::default();
            for chunk in chunks.values() {
                manifest.add_chunk(chunk);
            }

            manifest
        })
    })
}

#[cfg(test)]
mod tests {
    use tokio::io::AsyncWriteExt;
    use url::Url;

    use super::*;
    use crate::configuration::Apq;
    use crate::configuration::PersistedQueries;
    use crate::test_harness::mocks::persisted_queries::*;
    use crate::uplink::Endpoints;

    #[tokio::test(flavor = "multi_thread")]
    async fn poller_can_get_operation_bodies() {
        let (id, body, manifest) = fake_manifest();
        let (_mock_guard, uplink_config) = mock_pq_uplink(&manifest).await;
        let manifest_manager = PersistedQueryManifestPoller::new(
            Configuration::fake_builder()
                .uplink(uplink_config)
                .build()
                .unwrap(),
        )
        .await
        .unwrap();
        assert_eq!(manifest_manager.get_operation_body(&id, None), Some(body))
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn poller_wont_start_without_uplink_connection() {
        let uplink_endpoint = Url::parse("https://definitely.not.uplink").unwrap();
        assert!(
            PersistedQueryManifestPoller::new(
                Configuration::fake_builder()
                    .uplink(UplinkConfig::for_tests(Endpoints::fallback(vec![
                        uplink_endpoint
                    ])))
                    .build()
                    .unwrap(),
            )
            .await
            .is_err()
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn poller_fails_over_on_gcs_failure() {
        let (_mock_server1, url1) = mock_pq_uplink_bad_gcs().await;
        let (id, body, manifest) = fake_manifest();
        let (_mock_guard2, url2) = mock_pq_uplink_one_endpoint(&manifest, None).await;
        let manifest_manager = PersistedQueryManifestPoller::new(
            Configuration::fake_builder()
                .uplink(UplinkConfig::for_tests(Endpoints::fallback(vec![
                    url1, url2,
                ])))
                .build()
                .unwrap(),
        )
        .await
        .unwrap();
        assert_eq!(manifest_manager.get_operation_body(&id, None), Some(body))
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn uses_local_manifest() {
        let (_, body, _) = fake_manifest();
        let id = "5678".to_string();

        let manifest_manager = PersistedQueryManifestPoller::new(
            Configuration::fake_builder()
                .apq(Apq::fake_new(Some(false)))
                .persisted_query(
                    PersistedQueries::builder()
                        .enabled(true)
                        .local_manifests(vec![
                            "tests/fixtures/persisted-queries-manifest.json".to_string(),
                        ])
                        .build(),
                )
                .build()
                .unwrap(),
        )
        .await
        .unwrap();
        assert_eq!(manifest_manager.get_operation_body(&id, None), Some(body))
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn hot_reload_config_enforcement() {
        let err = PersistedQueryManifestPoller::new(
            Configuration::fake_builder()
                .apq(Apq::fake_new(Some(false)))
                .persisted_query(PersistedQueries::builder().hot_reload(true).build())
                .build()
                .unwrap(),
        )
        .await
        .unwrap_err();
        assert_eq!(
            err.to_string(),
            "`persisted_queries.hot_reload` requires `local_manifests`"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn hot_reload_stream_initial_load() {
        let (_, body, _) = fake_manifest();
        let id = "5678".to_string();

        let manifest_manager = PersistedQueryManifestPoller::new(
            Configuration::fake_builder()
                .apq(Apq::fake_new(Some(false)))
                .persisted_query(
                    PersistedQueries::builder()
                        .enabled(true)
                        .local_manifests(vec![
                            "tests/fixtures/persisted-queries-manifest.json".to_string(),
                        ])
                        .hot_reload(true)
                        .build(),
                )
                .build()
                .unwrap(),
        )
        .await
        .unwrap();
        assert_eq!(manifest_manager.get_operation_body(&id, None), Some(body));
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn handles_empty_pq_manifest_from_uplink() {
        let (_mock_guard, uplink_config) = mock_empty_pq_uplink().await;
        let manifest_manager = PersistedQueryManifestPoller::new(
            Configuration::fake_builder()
                .uplink(uplink_config)
                .build()
                .unwrap(),
        )
        .await
        .unwrap();

        // Should successfully start up with empty manifest
        assert_eq!(manifest_manager.get_all_operations().len(), 0);
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn hot_reload_stream_reloads_on_file_change() {
        const FIXTURE_PATH: &str = "tests/fixtures/persisted-queries-manifest-hot-reload.json";
        // Note: this directly matches the contents of the file in the fixtures
        // directory in order to ensure the fixture is restored after we modify
        // it for this test.
        const ORIGINAL_MANIFEST_CONTENTS: &str = r#"{
    "format": "apollo-persisted-query-manifest",
    "version": 1,
    "operations": [
        {
            "id": "5678",
            "name": "typename",
            "type": "query",
            "body": "query { typename }"
        }
    ]
}
"#;

        const UPDATED_MANIFEST_CONTENTS: &str = r#"{
    "format": "apollo-persisted-query-manifest",
    "version": 1,
    "operations": [
        {
            "id": "1234",
            "name": "typename",
            "type": "query",
            "body": "query { typename }"
        }
    ]
}
"#;

        let original_id = "5678".to_string();
        let updated_id = "1234".to_string();
        let body = "query { typename }".to_string();

        let manifest_manager = PersistedQueryManifestPoller::new(
            Configuration::fake_builder()
                .apq(Apq::fake_new(Some(false)))
                .persisted_query(
                    PersistedQueries::builder()
                        .enabled(true)
                        .local_manifests(vec![FIXTURE_PATH.to_string()])
                        .hot_reload(true)
                        .build(),
                )
                .build()
                .unwrap(),
        )
        .await
        .unwrap();
        assert_eq!(
            manifest_manager.get_operation_body(&original_id, None),
            Some(body.clone())
        );

        // Change the file
        let mut file = tokio::fs::File::create(FIXTURE_PATH).await.unwrap();
        file.write_all(UPDATED_MANIFEST_CONTENTS.as_bytes())
            .await
            .unwrap();
        file.sync_all().await.unwrap();

        // Wait for the file to be reloaded
        tokio::time::sleep(std::time::Duration::from_secs(1)).await;
        // The original ID should be gone
        assert_eq!(
            manifest_manager.get_operation_body(&original_id, None),
            None
        );
        // The updated ID should be present
        assert_eq!(
            manifest_manager.get_operation_body(&updated_id, None),
            Some(body.clone())
        );

        // Cleanup, restore the original file
        let mut file = tokio::fs::File::create(FIXTURE_PATH).await.unwrap();
        file.write_all(ORIGINAL_MANIFEST_CONTENTS.as_bytes())
            .await
            .unwrap();
        file.sync_all().await.unwrap();

        // Ensure the restoration is successful
        tokio::time::sleep(std::time::Duration::from_secs(1)).await;
        assert_eq!(
            manifest_manager.get_operation_body(&original_id, None),
            Some(body)
        );
    }
}