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
use std::sync::Arc;

use apollo_compiler::Schema;
use apollo_federation::link::spec::Identity;
use tower::ServiceExt;

use crate::Context;
use crate::TestHarness;
use crate::metrics::FutureMetricsExt;
use crate::plugin::Plugin;
use crate::plugin::PluginInit;
use crate::plugin::test::MockRouterService;
use crate::plugin::test::MockSupergraphService;
use crate::plugins::progressive_override::Config;
use crate::plugins::progressive_override::JOIN_FIELD_DIRECTIVE_NAME;
use crate::plugins::progressive_override::JOIN_SPEC_VERSION_RANGE;
use crate::plugins::progressive_override::LABELS_TO_OVERRIDE_KEY;
use crate::plugins::progressive_override::ProgressiveOverridePlugin;
use crate::plugins::progressive_override::UNRESOLVED_LABELS_KEY;
use crate::services::RouterResponse;
use crate::services::SupergraphResponse;
use crate::services::layers::query_analysis::ParsedDocument;
use crate::services::router;
use crate::services::supergraph;

const SCHEMA: &str = include_str!("testdata/supergraph.graphql");
const SCHEMA_NO_USAGES: &str = include_str!("testdata/supergraph_no_usages.graphql");

#[test]
fn test_progressive_overrides_are_recognised_vor_join_v0_4_and_above() {
    let schema_for_version = |version| {
        format!(
            r#"
            schema
              @link(url: "https://specs.apollo.dev/link/v1.0")
              @link(url: "https://specs.apollo.dev/join/{}", for: EXECUTION)
              @link(url: "https://specs.apollo.dev/context/v0.1", for: SECURITY)

            directive @link(
              url: String
              as: String
              for: link__Purpose
              import: [link__Import]
            ) repeatable on SCHEMA
            scalar link__Import
            enum link__Purpose {{
              """
              `SECURITY` features provide metadata necessary to securely resolve fields.
              """
              SECURITY

              """
              `EXECUTION` features provide metadata necessary for operation execution.
              """
              EXECUTION
            }}
            directive @join__field repeatable on FIELD_DEFINITION | INPUT_FIELD_DEFINITION
            "#,
            version,
        )
    };

    let join_v3_schema = Schema::parse(schema_for_version("v0.3"), "test").unwrap();
    assert!(
        crate::spec::Schema::directive_name(
            &join_v3_schema,
            &Identity::join_identity(),
            JOIN_SPEC_VERSION_RANGE,
            &JOIN_FIELD_DIRECTIVE_NAME,
        )
        .is_none()
    );

    let join_v4_schema = Schema::parse(schema_for_version("v0.4"), "test").unwrap();
    assert!(
        crate::spec::Schema::directive_name(
            &join_v4_schema,
            &Identity::join_identity(),
            JOIN_SPEC_VERSION_RANGE,
            &JOIN_FIELD_DIRECTIVE_NAME,
        )
        .is_some()
    );

    let join_v5_schema = Schema::parse(schema_for_version("v0.5"), "test").unwrap();

    assert!(
        crate::spec::Schema::directive_name(
            &join_v5_schema,
            &Identity::join_identity(),
            JOIN_SPEC_VERSION_RANGE,
            &JOIN_FIELD_DIRECTIVE_NAME,
        )
        .is_some()
    )
}

#[tokio::test]
async fn plugin_disables_itself_with_no_progressive_override_usages() {
    let plugin = ProgressiveOverridePlugin::new(PluginInit::fake_new(
        Config {},
        Arc::new(SCHEMA_NO_USAGES.to_string()),
    ))
    .await
    .unwrap();

    assert!(!plugin.enabled);
}

#[tokio::test]
async fn plugin_enables_itself_with_progressive_override_usages() {
    let plugin = ProgressiveOverridePlugin::new(PluginInit::fake_new(
        Config {},
        Arc::new(SCHEMA.to_string()),
    ))
    .await
    .unwrap();

    assert!(plugin.enabled);
}

#[tokio::test]
async fn plugin_router_service_adds_all_arbitrary_labels_to_context() {
    // This test ensures that the _router_service_ adds all of the arbitrary
    // labels to the context so coprocessors can resolve them. At this stage,
    // there's no concern about any percentage-based labels yet.
    let mut mock_service = MockRouterService::new();
    mock_service.expect_call().returning(move |request| {
        let labels_on_context = request
            .context
            .get::<_, Vec<Arc<String>>>(UNRESOLVED_LABELS_KEY)
            .unwrap()
            .unwrap();

        // this plugin handles the percent-based labels, so we don't want to add
        // those to the context for other coprocessors to resolve
        assert!(!labels_on_context.contains(&Arc::new("percent(0)".to_string())));
        assert!(!labels_on_context.contains(&Arc::new("percent(100)".to_string())));
        assert!(labels_on_context.len() == 3);
        assert!(
            vec!["bar", "baz", "foo"]
                .into_iter()
                .all(|s| labels_on_context.contains(&Arc::new(s.to_string())))
        );
        RouterResponse::fake_builder().build()
    });

    let service_stack = ProgressiveOverridePlugin::new(PluginInit::fake_new(
        Config {},
        Arc::new(SCHEMA.to_string()),
    ))
    .await
    .unwrap()
    .router_service(mock_service.boxed());

    let _ = service_stack
        .oneshot(router::Request::fake_builder().build().unwrap())
        .await;
}

struct LabelAssertions {
    query: &'static str,
    expected_labels: Vec<&'static str>,
    absent_labels: Vec<&'static str>,
    labels_from_coprocessors: Vec<&'static str>,
}

// We're testing a few things with this function. For a given query, we want to
// assert:
// 1. The expected labels are present in the context
// 2. The absent labels are not present in the context
//
// Additionally, we can simulate the inclusion of any other labels that may have
// been provided by "coprocessors".
async fn assert_expected_and_absent_labels_for_supergraph_service(
    label_assertions: LabelAssertions,
) {
    let LabelAssertions {
        query,
        expected_labels,
        absent_labels,
        labels_from_coprocessors,
    } = label_assertions;

    let mut mock_service = MockSupergraphService::new();

    mock_service.expect_call().returning(move |request| {
        let labels_to_override = request
            .context
            .get::<_, Vec<String>>(LABELS_TO_OVERRIDE_KEY)
            .unwrap()
            .unwrap();

        for label in &expected_labels {
            assert!(labels_to_override.contains(&label.to_string()));
        }
        for label in &absent_labels {
            assert!(!labels_to_override.contains(&label.to_string()));
        }
        SupergraphResponse::fake_builder().build()
    });

    let service_stack = ProgressiveOverridePlugin::new(PluginInit::fake_new(
        Config {},
        Arc::new(SCHEMA.to_string()),
    ))
    .await
    .unwrap()
    .supergraph_service(mock_service.boxed());

    let schema = crate::spec::Schema::parse(
        include_str!("./testdata/supergraph.graphql"),
        &Default::default(),
    )
    .unwrap();
    let parsed_doc =
        crate::spec::Query::parse_document(query, None, &schema, &crate::Configuration::default())
            .unwrap();

    let context = Context::new();
    context
        .extensions()
        .with_lock(|mut lock| lock.insert::<ParsedDocument>(parsed_doc));

    context
        .insert(
            LABELS_TO_OVERRIDE_KEY,
            labels_from_coprocessors
                .iter()
                .map(|s| s.to_string())
                .collect::<Vec<_>>(),
        )
        .unwrap();

    let request = supergraph::Request::fake_builder()
        .context(context)
        .query(query)
        .build()
        .unwrap();

    let _ = service_stack.oneshot(request).await;
}

#[tokio::test]
async fn plugin_supergraph_service_adds_percent_labels_to_context() {
    let label_assertions = LabelAssertions {
        query: "{ percent100 { foo } }",
        expected_labels: vec!["percent(100)"],
        absent_labels: vec!["percent(0)"],
        labels_from_coprocessors: vec![],
    };
    assert_expected_and_absent_labels_for_supergraph_service(label_assertions).await;
}

#[tokio::test]
async fn plugin_supergraph_service_trims_extraneous_labels() {
    let label_assertions = LabelAssertions {
        query: "{ percent100 { foo } }",
        // the foo label is relevant to the `foo` field (and resolved by the
        // "coprocessor"), so we expect it to be preserved
        expected_labels: vec!["percent(100)", "foo"],
        // `baz` exists in the schema but is not relevant to this query, so we expect it to be trimmed
        // `bogus` is not in the schema at all, so we expect it to be trimmed
        absent_labels: vec!["percent(0)", "bogus", "baz"],
        labels_from_coprocessors: vec!["foo", "baz", "bogus"],
    };
    assert_expected_and_absent_labels_for_supergraph_service(label_assertions).await;
}

#[tokio::test]
async fn plugin_supergraph_service_trims_0pc_label() {
    let label_assertions = LabelAssertions {
        query: "{ percent0 { foo } }",
        expected_labels: vec!["foo"],
        // the router will always resolve percent(0) to false
        absent_labels: vec!["percent(0)"],
        labels_from_coprocessors: vec!["foo"],
    };
    assert_expected_and_absent_labels_for_supergraph_service(label_assertions).await;
}

async fn get_json_query_plan(query: &str) -> serde_json::Value {
    let schema = crate::spec::Schema::parse(
        include_str!("./testdata/supergraph.graphql"),
        &Default::default(),
    )
    .unwrap();
    let parsed_doc =
        crate::spec::Query::parse_document(query, None, &schema, &crate::Configuration::default())
            .unwrap();

    let context: Context = Context::new();
    context
        .extensions()
        .with_lock(|mut lock| lock.insert::<ParsedDocument>(parsed_doc));

    let request = supergraph::Request::fake_builder()
        .query(query)
        .context(context)
        .header("Apollo-Expose-Query-Plan", "true")
        .build()
        .unwrap();

    let supergraph_service = TestHarness::builder()
        .configuration_json(serde_json::json! {{
            "include_subgraph_errors": {
                "all": true
            },
            "plugins": {
                "experimental.expose_query_plan": true
            }
        }})
        .unwrap()
        .schema(SCHEMA)
        .build_supergraph()
        .await
        .unwrap();

    let response = supergraph_service
        .oneshot(request)
        .await
        .unwrap()
        .next_response()
        .await
        .unwrap();

    serde_json::to_value(response).unwrap()
}

#[tokio::test]
async fn non_overridden_field_yields_expected_query_plan() {
    // `percent0` and `foo` should both be resolved in `Subgraph2`
    let query_plan = get_json_query_plan("{ percent0 { foo } }").await;
    insta::assert_json_snapshot!(query_plan);
}

#[tokio::test]
async fn overridden_field_yields_expected_query_plan() {
    // `percent100` should be overridden to `Subgraph1` while `foo` is not, so
    // we expect a query plan with 2 fetches: the first to `Subgraph1` and a
    // serial fetch after to resolve `foo` in `Subgraph2`
    let query_plan = get_json_query_plan("{ percent100 { foo } }").await;
    insta::assert_json_snapshot!(query_plan);
}

async fn query_with_labels(query: &str, labels_from_coprocessors: Vec<&str>) {
    let mut mock_service = MockSupergraphService::new();
    mock_service
        .expect_call()
        .returning(|_| SupergraphResponse::fake_builder().build());

    let service_stack = ProgressiveOverridePlugin::new(PluginInit::fake_new(
        Config {},
        Arc::new(SCHEMA.to_string()),
    ))
    .await
    .unwrap()
    .supergraph_service(mock_service.boxed());

    let schema = crate::spec::Schema::parse(
        include_str!("./testdata/supergraph.graphql"),
        &Default::default(),
    )
    .unwrap();
    let parsed_doc =
        crate::spec::Query::parse_document(query, None, &schema, &crate::Configuration::default())
            .unwrap();

    let context = Context::new();
    context
        .extensions()
        .with_lock(|mut lock| lock.insert::<ParsedDocument>(parsed_doc));

    context
        .insert(
            LABELS_TO_OVERRIDE_KEY,
            labels_from_coprocessors
                .iter()
                .map(|s| s.to_string())
                .collect::<Vec<_>>(),
        )
        .unwrap();

    let request = supergraph::Request::fake_builder()
        .context(context)
        .query(query)
        .build()
        .unwrap();

    let _ = service_stack.oneshot(request).await;
}

#[tokio::test]
async fn query_with_overridden_labels_metrics() {
    async {
        query_with_labels("{ percent100 { foo } }", vec![]).await;
        assert_counter!(
            "apollo.router.operations.override.query",
            1,
            query.label_count = 2
        );
    }
    .with_metrics()
    .await;
}

#[tokio::test]
async fn query_with_externally_resolved_labels_metrics() {
    async {
        query_with_labels("{ percent100 { foo } }", vec!["foo"]).await;
        assert_counter!(
            "apollo.router.operations.override.query",
            1,
            query.label_count = 2
        );
        assert_counter!("apollo.router.operations.override.external", 1);
    }
    .with_metrics()
    .await;
}