apollo-federation 2.13.1

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

use apollo_compiler::executable;

use super::*;
use crate::display_helpers::State;
use crate::display_helpers::write_indented_lines;

impl QueryPlan {
    fn write_indented(&self, state: &mut State<'_, '_>) -> fmt::Result {
        let Self {
            node,
            statistics: _,
        } = self;
        state.write("QueryPlan {")?;
        if let Some(node) = node {
            state.indent()?;
            node.write_indented(state)?;
            state.dedent()?;
        }
        state.write("}")
    }
}

impl TopLevelPlanNode {
    fn write_indented(&self, state: &mut State<'_, '_>) -> fmt::Result {
        match self {
            Self::Subscription(node) => node.write_indented(state),
            Self::Fetch(node) => node.write_indented(state),
            Self::Sequence(node) => node.write_indented(state),
            Self::Parallel(node) => node.write_indented(state),
            Self::Flatten(node) => node.write_indented(state),
            Self::Defer(node) => node.write_indented(state),
            Self::Condition(node) => node.write_indented(state),
        }
    }
}

impl PlanNode {
    fn write_indented(&self, state: &mut State<'_, '_>) -> fmt::Result {
        match self {
            Self::Fetch(node) => node.write_indented(state),
            Self::Sequence(node) => node.write_indented(state),
            Self::Parallel(node) => node.write_indented(state),
            Self::Flatten(node) => node.write_indented(state),
            Self::Defer(node) => node.write_indented(state),
            Self::Condition(node) => node.write_indented(state),
        }
    }
}

impl SubscriptionNode {
    fn write_indented(&self, state: &mut State<'_, '_>) -> fmt::Result {
        let Self { primary, rest } = self;
        state.write("Subscription {")?;
        state.indent()?;

        state.write("Primary: {")?;
        state.indent()?;
        primary.write_indented(state)?;
        state.dedent()?;
        state.write("},")?;

        if let Some(rest) = rest {
            state.new_line()?;
            state.write("Rest: {")?;
            state.indent()?;
            rest.write_indented(state)?;
            state.dedent()?;
            state.write("},")?;
        }

        state.dedent()?;
        state.write("},")
    }
}

impl FetchNode {
    fn write_indented(&self, state: &mut State<'_, '_>) -> fmt::Result {
        let Self {
            subgraph_name,
            id,
            variable_usages: _,
            requires,
            operation_document,
            operation_name: _,
            operation_kind: _,
            input_rewrites: _,
            output_rewrites: _,
            context_rewrites: _,
        } = self;
        state.write(format_args!("Fetch(service: {subgraph_name:?}"))?;
        if let Some(id) = id {
            state.write(format_args!(", id: {id:?}"))?;
        }
        state.write(") {")?;
        state.indent()?;

        if !requires.is_empty() {
            write_requires_selections(state, requires)?;
            state.write(" =>")?;
            state.new_line()?;
        }
        write_operation(
            state,
            operation_document.as_parsed().map_err(|_| fmt::Error)?,
        )?;

        state.dedent()?;
        state.write("},")
    }
}

impl SequenceNode {
    fn write_indented(&self, state: &mut State<'_, '_>) -> fmt::Result {
        let Self { nodes } = self;
        state.write("Sequence {")?;

        write_indented_lines(state, nodes, |state, node| node.write_indented(state))?;

        state.write("},")
    }
}

impl ParallelNode {
    fn write_indented(&self, state: &mut State<'_, '_>) -> fmt::Result {
        let Self { nodes } = self;
        state.write("Parallel {")?;

        write_indented_lines(state, nodes, |state, node| node.write_indented(state))?;

        state.write("},")
    }
}

impl FlattenNode {
    fn write_indented(&self, state: &mut State<'_, '_>) -> fmt::Result {
        let Self { path, node } = self;
        state.write("Flatten(path: \"")?;
        if let Some((first, rest)) = path.split_first() {
            state.write(first)?;
            for element in rest {
                state.write(".")?;
                state.write(element)?;
            }
        }
        state.write("\") {")?;
        state.indent()?;

        node.write_indented(state)?;

        state.dedent()?;
        state.write("},")
    }
}

impl ConditionNode {
    fn write_indented(&self, state: &mut State<'_, '_>) -> fmt::Result {
        let Self {
            condition_variable,
            if_clause,
            else_clause,
        } = self;
        match (if_clause, else_clause) {
            (Some(if_clause), Some(else_clause)) => {
                state.write(format_args!("Condition(if: ${condition_variable}) {{"))?;
                state.indent()?;

                state.write("Then {")?;
                state.indent()?;
                if_clause.write_indented(state)?;
                state.dedent()?;
                state.write("}")?;

                state.write(" Else {")?;
                state.indent()?;
                else_clause.write_indented(state)?;
                state.dedent()?;
                state.write("},")?;

                state.dedent()?;
                state.write("},")
            }

            (Some(if_clause), None) => {
                state.write(format_args!("Include(if: ${condition_variable}) {{"))?;
                state.indent()?;

                if_clause.write_indented(state)?;

                state.dedent()?;
                state.write("},")
            }

            (None, Some(else_clause)) => {
                state.write(format_args!("Skip(if: ${condition_variable}) {{"))?;
                state.indent()?;

                else_clause.write_indented(state)?;

                state.dedent()?;
                state.write("},")
            }

            // Shouldn’t happen?
            (None, None) => state.write("Condition {}"),
        }
    }
}

impl DeferNode {
    fn write_indented(&self, state: &mut State<'_, '_>) -> fmt::Result {
        let Self { primary, deferred } = self;
        state.write("Defer {")?;
        state.indent()?;

        primary.write_indented(state)?;
        if !deferred.is_empty() {
            state.write(" [")?;
            write_indented_lines(state, deferred, |state, deferred| {
                deferred.write_indented(state)
            })?;
            state.write("]")?;
        }

        state.dedent()?;
        state.write("},")
    }
}

impl PrimaryDeferBlock {
    fn write_indented(&self, state: &mut State<'_, '_>) -> fmt::Result {
        let Self {
            sub_selection,
            node,
        } = self;
        state.write("Primary {")?;
        if sub_selection.is_some() || node.is_some() {
            if let Some(sub_selection) = sub_selection {
                state.indent()?;
                state.write(sub_selection)?;
                if node.is_some() {
                    state.write(":")?;
                    state.new_line()?;
                }
            } else {
                // Indent to match the Some() case
                state.indent()?;
            }

            if let Some(node) = node {
                node.write_indented(state)?;
            }

            state.dedent()?;
        }
        state.write("},")
    }
}

impl DeferredDeferBlock {
    fn write_indented(&self, state: &mut State<'_, '_>) -> fmt::Result {
        let Self {
            depends,
            label,
            query_path,
            sub_selection,
            node,
        } = self;

        state.write("Deferred(depends: [")?;
        if let Some((DeferredDependency { id }, rest)) = depends.split_first() {
            state.write(id)?;
            for DeferredDependency { id } in rest {
                state.write(", ")?;
                state.write(id)?;
            }
        }
        state.write("], path: \"")?;
        if let Some((first, rest)) = query_path.split_first() {
            state.write(first)?;
            for element in rest {
                state.write("/")?;
                state.write(element)?;
            }
        }
        state.write("\"")?;
        if let Some(label) = label {
            state.write_fmt(format_args!(r#", label: "{label}""#))?;
        }
        state.write(") {")?;

        if sub_selection.is_some() || node.is_some() {
            state.indent()?;

            if let Some(sub_selection) = sub_selection {
                state.write(sub_selection)?;
                state.write(":")?;
            }
            if sub_selection.is_some() && node.is_some() {
                state.new_line()?;
            }
            if let Some(node) = node {
                node.write_indented(state)?;
            }

            state.dedent()?;
        }

        state.write("},")
    }
}

/// When we serialize a query plan, we want to serialize the operation
/// but not show the root level `query` definition or the `_entities` call.
/// This function flattens those nodes to only show their selection sets
fn write_operation(
    state: &mut State<'_, '_>,
    operation_document: &ExecutableDocument,
) -> fmt::Result {
    let operation = operation_document
        .operations
        .get(None)
        .expect("expected a single-operation document");
    write_selections(state, &operation.selection_set.selections)?;
    for fragment in operation_document.fragments.values() {
        state.write("\n\n")?; // new line without indentation (since `fragment` adds indentation)
        state.write(
            fragment
                .serialize()
                .initial_indent_level(state.indent_level()),
        )?
    }
    Ok(())
}

fn write_selections(
    state: &mut State<'_, '_>,
    mut selections: &[executable::Selection],
) -> fmt::Result {
    if let Some(executable::Selection::Field(field)) = selections.first()
        && field.name == "_entities"
    {
        selections = &field.selection_set.selections
    }
    state.write("{")?;

    // Manually indent and write the newline
    // to prevent a duplicate indent from `.new_line()` and `.initial_indent_level()`.
    state.indent_no_new_line();
    for sel in selections {
        state.write("\n")?;
        state.write(sel.serialize().initial_indent_level(state.indent_level()))?;
    }
    state.dedent()?;

    state.write("}")
}

fn write_requires_selections(
    state: &mut State<'_, '_>,
    selections: &[requires_selection::Selection],
) -> fmt::Result {
    state.write("{")?;

    // Manually indent and write the newline
    // to prevent a duplicate indent from `.new_line()` and `.initial_indent_level()`.
    state.indent()?;
    if let Some((first, rest)) = selections.split_first() {
        write_requires_selection(state, first)?;
        for sel in rest {
            state.new_line()?;
            write_requires_selection(state, sel)?;
        }
    }
    state.dedent()?;

    state.write("}")
}

fn write_requires_selection(
    state: &mut State<'_, '_>,
    selection: &requires_selection::Selection,
) -> fmt::Result {
    match selection {
        requires_selection::Selection::Field(requires_selection::Field {
            alias,
            name,
            selections,
        }) => {
            if let Some(alias) = alias {
                state.write(alias)?;
                state.write(": ")?;
            }
            state.write(name)?;
            if !selections.is_empty() {
                state.write(" ")?;
                write_requires_selections(state, selections)?;
            }
        }
        requires_selection::Selection::InlineFragment(requires_selection::InlineFragment {
            type_condition,
            selections,
        }) => {
            if let Some(type_name) = type_condition {
                state.write("... on ")?;
                state.write(type_name)?;
                state.write(" ")?;
            } else {
                state.write("... ")?;
            }
            write_requires_selections(state, selections)?;
        }
    }
    Ok(())
}

impl fmt::Display for requires_selection::Selection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_requires_selection(&mut State::new(f), self)
    }
}

/// PORT_NOTE: Corresponds to `GroupPath.updatedResponsePath` in `buildPlan.ts`
impl fmt::Display for FetchDataPathElement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Key(name, conditions) => {
                f.write_str(name)?;
                write_conditions(conditions, f)
            }
            Self::AnyIndex(conditions) => {
                f.write_str("@")?;
                write_conditions(conditions, f)
            }
            Self::TypenameEquals(name) => write!(f, "... on {name}"),
            Self::Parent => write!(f, ".."),
        }
    }
}

fn write_conditions(conditions: &Option<Vec<Name>>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    if let Some(conditions) = conditions {
        write!(f, "|[{}]", conditions.join(","))
    } else {
        Ok(())
    }
}

impl fmt::Display for QueryPathElement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Field { response_key } => f.write_str(response_key),
            Self::InlineFragment { type_condition } => write!(f, "... on {type_condition}"),
        }
    }
}

macro_rules! impl_display {
    ($( $Ty: ty )+) => {
        $(
            impl fmt::Display for $Ty {
                fn fmt(&self, output: &mut fmt::Formatter<'_>) -> fmt::Result {
                    self.write_indented(&mut State::new(output))
                }
            }
        )+
    };
}

impl_display! {
    QueryPlan
    TopLevelPlanNode
    PlanNode
    SubscriptionNode
    FetchNode
    SequenceNode
    ParallelNode
    FlattenNode
    ConditionNode
    DeferNode
    PrimaryDeferBlock
    DeferredDeferBlock
}