apollo-supergraph 0.0.1

Apollo Federation Supergraph
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
use crate::merge::merge_subgraphs;
use apollo_compiler::ast::Directives;
use apollo_compiler::schema::ExtendedType;
use apollo_compiler::Schema;
use apollo_subgraph::Subgraph;

pub mod database;
pub mod merge;

type MergeError = &'static str;

// TODO: Same remark as in other crates: we need to define this more cleanly, and probably need
// some "federation errors" crate.
#[derive(Debug)]
pub struct SupergraphError {
    pub msg: String,
}

pub struct Supergraph {
    pub schema: Schema,
}

impl Supergraph {
    pub fn new(schema_str: &str) -> Self {
        let schema = Schema::parse(schema_str, "schema.graphql");

        // TODO: like for subgraphs, it would nice if `Supergraph` was always representing
        // a valid supergraph (which is simpler than for subgraph, but still at least means
        // that it's valid graphQL in the first place, and that it has the `join` spec).

        Self { schema }
    }

    pub fn compose(subgraphs: Vec<&Subgraph>) -> Result<Self, MergeError> {
        let merge_result = match merge_subgraphs(subgraphs) {
            Ok(success) => Ok(Self::new(success.schema.to_string().as_str())),
            // TODO handle errors
            Err(_) => Err("failed to compose"),
        };
        merge_result
    }

    /// Generates API schema from the supergraph schema.
    pub fn to_api_schema(&self) -> Schema {
        let mut api_schema = self.schema.clone();

        // remove schema directives
        api_schema.schema_definition.make_mut().directives.clear();

        // remove known internal types
        api_schema.types.retain(|type_name, graphql_type| {
            !is_join_type(type_name.as_str())
                && !graphql_type
                    .directives()
                    .iter()
                    .any(|d| d.name.eq("inaccessible"))
        });
        // remove directive applications
        for (_, graphql_type) in api_schema.types.iter_mut() {
            match graphql_type {
                ExtendedType::Scalar(scalar) => {
                    scalar.make_mut().directives.clear();
                }
                ExtendedType::Object(object) => {
                    let object = object.make_mut();
                    object.directives.clear();
                    object
                        .fields
                        .retain(|_, field| !is_inaccessible_applied(&field.directives));
                    for (_, field) in object.fields.iter_mut() {
                        let field = field.make_mut();
                        field.directives.clear();
                        field
                            .arguments
                            .retain(|arg| !is_inaccessible_applied(&arg.directives));
                        for arg in field.arguments.iter_mut() {
                            arg.make_mut().directives.clear();
                        }
                    }
                }
                ExtendedType::Interface(intf) => {
                    let intf = intf.make_mut();
                    intf.directives.clear();
                    intf.fields
                        .retain(|_, field| !is_inaccessible_applied(&field.directives));
                    for (_, field) in intf.fields.iter_mut() {
                        let field = field.make_mut();
                        field.directives.clear();
                        for arg in field.arguments.iter_mut() {
                            arg.make_mut().directives.clear();
                        }
                    }
                }
                ExtendedType::Union(union) => {
                    union.make_mut().directives.clear();
                }
                ExtendedType::Enum(enum_type) => {
                    let enum_type = enum_type.make_mut();
                    enum_type.directives.clear();
                    enum_type
                        .values
                        .retain(|_, enum_value| !is_inaccessible_applied(&enum_value.directives));
                    for (_, enum_value) in enum_type.values.iter_mut() {
                        enum_value.make_mut().directives.clear();
                    }
                }
                ExtendedType::InputObject(input_object) => {
                    let input_object = input_object.make_mut();
                    input_object.directives.clear();
                    input_object
                        .fields
                        .retain(|_, input_field| !is_inaccessible_applied(&input_field.directives));
                    for (_, input_field) in input_object.fields.iter_mut() {
                        input_field.make_mut().directives.clear();
                    }
                }
            }
        }
        // remove directives
        api_schema.directive_definitions.clear();

        api_schema
    }
}

impl From<Schema> for Supergraph {
    fn from(schema: Schema) -> Self {
        Self { schema }
    }
}

const JOIN_TYPES: [&str; 4] = [
    "join__Graph",
    "link__Purpose",
    "join__FieldSet",
    "link__Import",
];
fn is_join_type(type_name: &str) -> bool {
    JOIN_TYPES.contains(&type_name)
}

fn is_inaccessible_applied(directives: &Directives) -> bool {
    directives.iter().any(|d| d.name.eq("inaccessible"))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn print_sdl(schema: &Schema) -> String {
        let mut schema = schema.clone();
        schema.types.sort_keys();
        schema.directive_definitions.sort_keys();
        schema.to_string()
    }

    #[test]
    fn can_extract_subgraph() {
        // TODO: not actually implemented; just here to give a sense of the API.
        let schema = r#"
          schema
            @link(url: "https://specs.apollo.dev/link/v1.0")
            @link(url: "https://specs.apollo.dev/join/v0.3", for: EXECUTION)
          {
            query: Query
          }

          directive @join__enumValue(graph: join__Graph!) repeatable on ENUM_VALUE

          directive @join__field(graph: join__Graph, requires: join__FieldSet, provides: join__FieldSet, type: String, external: Boolean, override: String, usedOverridden: Boolean) repeatable on FIELD_DEFINITION | INPUT_FIELD_DEFINITION

          directive @join__graph(name: String!, url: String!) on ENUM_VALUE

          directive @join__implements(graph: join__Graph!, interface: String!) repeatable on OBJECT | INTERFACE

          directive @join__type(graph: join__Graph!, key: join__FieldSet, extension: Boolean! = false, resolvable: Boolean! = true, isInterfaceObject: Boolean! = false) repeatable on OBJECT | INTERFACE | UNION | ENUM | INPUT_OBJECT | SCALAR

          directive @join__unionMember(graph: join__Graph!, member: String!) repeatable on UNION

          directive @link(url: String, as: String, for: link__Purpose, import: [link__Import]) repeatable on SCHEMA

          enum E
            @join__type(graph: SUBGRAPH2)
          {
            V1 @join__enumValue(graph: SUBGRAPH2)
            V2 @join__enumValue(graph: SUBGRAPH2)
          }

          scalar join__FieldSet

          enum join__Graph {
            SUBGRAPH1 @join__graph(name: "Subgraph1", url: "https://Subgraph1")
            SUBGRAPH2 @join__graph(name: "Subgraph2", url: "https://Subgraph2")
          }

          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
          }

          type Query
            @join__type(graph: SUBGRAPH1)
            @join__type(graph: SUBGRAPH2)
          {
            t: T @join__field(graph: SUBGRAPH1)
          }

          type S
            @join__type(graph: SUBGRAPH1)
          {
            x: Int
          }

          type T
            @join__type(graph: SUBGRAPH1, key: "k")
            @join__type(graph: SUBGRAPH2, key: "k")
          {
            k: ID
            a: Int @join__field(graph: SUBGRAPH2)
            b: String @join__field(graph: SUBGRAPH2)
          }

          union U
            @join__type(graph: SUBGRAPH1)
            @join__unionMember(graph: SUBGRAPH1, member: "S")
            @join__unionMember(graph: SUBGRAPH1, member: "T")
           = S | T
        "#;

        let supergraph = Supergraph::new(schema);
        let _subgraphs = database::extract_subgraphs(&supergraph)
            .expect("Should have been able to extract subgraphs");
        // TODO: actual assertions on the subgraph once it's actually implemented.
    }

    #[test]
    fn can_compose_supergraph() {
        let s1 = Subgraph::parse_and_expand(
            "Subgraph1",
            "https://subgraph1",
            r#"
                type Query {
                  t: T
                }
        
                type T @key(fields: "k") {
                  k: ID
                }
        
                type S {
                  x: Int
                }
        
                union U = S | T
            "#,
        )
        .unwrap();
        let s2 = Subgraph::parse_and_expand(
            "Subgraph2",
            "https://subgraph2",
            r#"
                type T @key(fields: "k") {
                  k: ID
                  a: Int
                  b: String
                }
                
                enum E {
                  V1
                  V2
                }
            "#,
        )
        .unwrap();

        let supergraph = Supergraph::compose(vec![&s1, &s2]).unwrap();
        let expected_supergraph_sdl = r#"schema @link(url: "https://specs.apollo.dev/link/v1.0") @link(url: "https://specs.apollo.dev/join/v0.3", for: EXECUTION) {
  query: Query
}

directive @join__enumValue(graph: join__Graph!) repeatable on ENUM_VALUE

directive @join__field(graph: join__Graph, requires: join__FieldSet, provides: join__FieldSet, type: String, external: Boolean, override: String, usedOverridden: Boolean) repeatable on FIELD_DEFINITION | INPUT_FIELD_DEFINITION

directive @join__graph(name: String!, url: String!) on ENUM_VALUE

directive @join__implements(graph: join__Graph!, interface: String!) repeatable on INTERFACE | OBJECT

directive @join__type(graph: join__Graph!, key: join__FieldSet, extension: Boolean! = false, resolvable: Boolean! = true, isInterfaceObject: Boolean! = false) repeatable on ENUM | INPUT_OBJECT | INTERFACE | OBJECT | SCALAR | UNION

directive @join__unionMember(graph: join__Graph!, member: String!) repeatable on UNION

directive @link(url: String, as: String, for: link__Purpose, import: [link__Import]) repeatable on SCHEMA

enum E @join__type(graph: SUBGRAPH2) {
  V1 @join__enumValue(graph: SUBGRAPH2)
  V2 @join__enumValue(graph: SUBGRAPH2)
}

type Query @join__type(graph: SUBGRAPH1) @join__type(graph: SUBGRAPH2) {
  t: T @join__field(graph: SUBGRAPH1)
}

type S @join__type(graph: SUBGRAPH1) {
  x: Int
}

type T @join__type(graph: SUBGRAPH1, key: "k") @join__type(graph: SUBGRAPH2, key: "k") {
  k: ID
  a: Int @join__field(graph: SUBGRAPH2)
  b: String @join__field(graph: SUBGRAPH2)
}

union U @join__type(graph: SUBGRAPH1) @join__unionMember(graph: SUBGRAPH1, member: "S") @join__unionMember(graph: SUBGRAPH1, member: "T") = S | T

scalar join__FieldSet

enum join__Graph {
  SUBGRAPH1 @join__graph(name: "Subgraph1", url: "https://subgraph1")
  SUBGRAPH2 @join__graph(name: "Subgraph2", url: "https://subgraph2")
}

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
}
"#;
        assert_eq!(print_sdl(&supergraph.schema), expected_supergraph_sdl);

        let expected_api_schema = r#"enum E {
  V1
  V2
}

type Query {
  t: T
}

type S {
  x: Int
}

type T {
  k: ID
  a: Int
  b: String
}

union U = S | T
"#;

        assert_eq!(print_sdl(&supergraph.to_api_schema()), expected_api_schema);
    }

    #[test]
    fn can_compose_with_descriptions() {
        let s1 = Subgraph::parse_and_expand(
            "Subgraph1",
            "https://subgraph1",
            r#"
                "The foo directive description"
                directive @foo(url: String) on FIELD
    
                "A cool schema"
                schema {
                  query: Query
                }
    
                """
                Available queries
                Not much yet
                """
                type Query {
                  "Returns tea"
                  t(
                    "An argument that is very important"
                    x: String!
                  ): String
                }
            "#,
        )
        .unwrap();

        let s2 = Subgraph::parse_and_expand(
            "Subgraph2",
            "https://subgraph2",
            r#"
                "The foo directive description"
                directive @foo(url: String) on FIELD
    
                "An enum"
                enum E {
                  "The A value"
                  A
                  "The B value"
                  B
                }
            "#,
        )
        .unwrap();

        let expected_supergraph_sdl = r#""A cool schema"
schema @link(url: "https://specs.apollo.dev/link/v1.0") @link(url: "https://specs.apollo.dev/join/v0.3", for: EXECUTION) {
  query: Query
}

"The foo directive description"
directive @foo(url: String) on FIELD

directive @join__enumValue(graph: join__Graph!) repeatable on ENUM_VALUE

directive @join__field(graph: join__Graph, requires: join__FieldSet, provides: join__FieldSet, type: String, external: Boolean, override: String, usedOverridden: Boolean) repeatable on FIELD_DEFINITION | INPUT_FIELD_DEFINITION

directive @join__graph(name: String!, url: String!) on ENUM_VALUE

directive @join__implements(graph: join__Graph!, interface: String!) repeatable on INTERFACE | OBJECT

directive @join__type(graph: join__Graph!, key: join__FieldSet, extension: Boolean! = false, resolvable: Boolean! = true, isInterfaceObject: Boolean! = false) repeatable on ENUM | INPUT_OBJECT | INTERFACE | OBJECT | SCALAR | UNION

directive @join__unionMember(graph: join__Graph!, member: String!) repeatable on UNION

directive @link(url: String, as: String, for: link__Purpose, import: [link__Import]) repeatable on SCHEMA

"An enum"
enum E @join__type(graph: SUBGRAPH2) {
  "The A value"
  A @join__enumValue(graph: SUBGRAPH2)
  "The B value"
  B @join__enumValue(graph: SUBGRAPH2)
}

"Available queries\nNot much yet"
type Query @join__type(graph: SUBGRAPH1) @join__type(graph: SUBGRAPH2) {
  "Returns tea"
  t(
    "An argument that is very important"
    x: String!,
  ): String @join__field(graph: SUBGRAPH1)
}

scalar join__FieldSet

enum join__Graph {
  SUBGRAPH1 @join__graph(name: "Subgraph1", url: "https://subgraph1")
  SUBGRAPH2 @join__graph(name: "Subgraph2", url: "https://subgraph2")
}

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
}
"#;
        let supergraph = Supergraph::compose(vec![&s1, &s2]).unwrap();
        // TODO currently printer does not respect multi line comments
        // TODO printer also adds extra comma after arguments
        assert_eq!(print_sdl(&supergraph.schema), expected_supergraph_sdl);

        let expected_api_schema = r#""A cool schema"
schema {
  query: Query
}

"An enum"
enum E {
  "The A value"
  A
  "The B value"
  B
}

"Available queries\nNot much yet"
type Query {
  "Returns tea"
  t(
    "An argument that is very important"
    x: String!,
  ): String
}
"#;
        assert_eq!(print_sdl(&supergraph.to_api_schema()), expected_api_schema);
    }

    #[test]
    fn can_compose_types_from_different_subgraphs() {
        let s1 = Subgraph::parse_and_expand(
            "SubgraphA",
            "https://subgraphA",
            r#"
                type Query {
                    products: [Product!]
                }

                type Product {
                    sku: String!
                    name: String!
                }
            "#,
        )
        .unwrap();

        let s2 = Subgraph::parse_and_expand(
            "SubgraphB",
            "https://subgraphB",
            r#"
                type User {
                    name: String
                    email: String!
                }
            "#,
        )
        .unwrap();

        let expected_supergraph_sdl = r#"schema @link(url: "https://specs.apollo.dev/link/v1.0") @link(url: "https://specs.apollo.dev/join/v0.3", for: EXECUTION) {
  query: Query
}

directive @join__enumValue(graph: join__Graph!) repeatable on ENUM_VALUE

directive @join__field(graph: join__Graph, requires: join__FieldSet, provides: join__FieldSet, type: String, external: Boolean, override: String, usedOverridden: Boolean) repeatable on FIELD_DEFINITION | INPUT_FIELD_DEFINITION

directive @join__graph(name: String!, url: String!) on ENUM_VALUE

directive @join__implements(graph: join__Graph!, interface: String!) repeatable on INTERFACE | OBJECT

directive @join__type(graph: join__Graph!, key: join__FieldSet, extension: Boolean! = false, resolvable: Boolean! = true, isInterfaceObject: Boolean! = false) repeatable on ENUM | INPUT_OBJECT | INTERFACE | OBJECT | SCALAR | UNION

directive @join__unionMember(graph: join__Graph!, member: String!) repeatable on UNION

directive @link(url: String, as: String, for: link__Purpose, import: [link__Import]) repeatable on SCHEMA

type Product @join__type(graph: SUBGRAPHA) {
  sku: String!
  name: String!
}

type Query @join__type(graph: SUBGRAPHA) @join__type(graph: SUBGRAPHB) {
  products: [Product!] @join__field(graph: SUBGRAPHA)
}

type User @join__type(graph: SUBGRAPHB) {
  name: String
  email: String!
}

scalar join__FieldSet

enum join__Graph {
  SUBGRAPHA @join__graph(name: "SubgraphA", url: "https://subgraphA")
  SUBGRAPHB @join__graph(name: "SubgraphB", url: "https://subgraphB")
}

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
}
"#;
        let supergraph = Supergraph::compose(vec![&s1, &s2]).unwrap();
        assert_eq!(print_sdl(&supergraph.schema), expected_supergraph_sdl);

        let expected_api_schema = r#"type Product {
  sku: String!
  name: String!
}

type Query {
  products: [Product!]
}

type User {
  name: String
  email: String!
}
"#;

        assert_eq!(print_sdl(&supergraph.to_api_schema()), expected_api_schema);
    }

    #[test]
    fn compose_removes_federation_directives() {
        let s1 = Subgraph::parse_and_expand(
            "SubgraphA",
            "https://subgraphA",
            r#"
                extend schema @link(url: "https://specs.apollo.dev/federation/v2.5", import: [ "@key", "@provides", "@external" ])
                
                type Query {
                  products: [Product!] @provides(fields: "name")
                }
        
                type Product @key(fields: "sku") {
                  sku: String!
                  name: String! @external
                }
            "#,
        )
        .unwrap();

        let s2 = Subgraph::parse_and_expand(
            "SubgraphB",
            "https://subgraphB",
            r#"
                extend schema @link(url: "https://specs.apollo.dev/federation/v2.5", import: [ "@key", "@shareable" ])
            
                type Product @key(fields: "sku") {
                  sku: String!
                  name: String! @shareable
                }
            "#,
        )
        .unwrap();

        let expected_supergraph_sdl = r#"schema @link(url: "https://specs.apollo.dev/link/v1.0") @link(url: "https://specs.apollo.dev/join/v0.3", for: EXECUTION) {
  query: Query
}

directive @join__enumValue(graph: join__Graph!) repeatable on ENUM_VALUE

directive @join__field(graph: join__Graph, requires: join__FieldSet, provides: join__FieldSet, type: String, external: Boolean, override: String, usedOverridden: Boolean) repeatable on FIELD_DEFINITION | INPUT_FIELD_DEFINITION

directive @join__graph(name: String!, url: String!) on ENUM_VALUE

directive @join__implements(graph: join__Graph!, interface: String!) repeatable on INTERFACE | OBJECT

directive @join__type(graph: join__Graph!, key: join__FieldSet, extension: Boolean! = false, resolvable: Boolean! = true, isInterfaceObject: Boolean! = false) repeatable on ENUM | INPUT_OBJECT | INTERFACE | OBJECT | SCALAR | UNION

directive @join__unionMember(graph: join__Graph!, member: String!) repeatable on UNION

directive @link(url: String, as: String, for: link__Purpose, import: [link__Import]) repeatable on SCHEMA

type Product @join__type(graph: SUBGRAPHA, key: "sku") @join__type(graph: SUBGRAPHB, key: "sku") {
  sku: String!
  name: String! @join__field(graph: SUBGRAPHA, external: true) @join__field(graph: SUBGRAPHB)
}

type Query @join__type(graph: SUBGRAPHA) @join__type(graph: SUBGRAPHB) {
  products: [Product!] @join__field(graph: SUBGRAPHA, provides: "name")
}

scalar join__FieldSet

enum join__Graph {
  SUBGRAPHA @join__graph(name: "SubgraphA", url: "https://subgraphA")
  SUBGRAPHB @join__graph(name: "SubgraphB", url: "https://subgraphB")
}

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
}
"#;

        let supergraph = Supergraph::compose(vec![&s1, &s2]).unwrap();
        assert_eq!(print_sdl(&supergraph.schema), expected_supergraph_sdl);

        let expected_api_schema = r#"type Product {
  sku: String!
  name: String!
}

type Query {
  products: [Product!]
}
"#;

        assert_eq!(print_sdl(&supergraph.to_api_schema()), expected_api_schema);
    }
}