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
use std::fmt;
use std::fmt::Display;
use std::hash::BuildHasher;
use std::hash::Hash;
use std::hash::Hasher;
use std::ops::Deref;
use std::sync::Arc;
use std::sync::OnceLock;

use apollo_compiler::Name;
use apollo_compiler::Node;
use apollo_compiler::collections::IndexSet;
use apollo_compiler::executable;
use serde::Serialize;

use super::DEFER_DIRECTIVE_NAME;
use super::DEFER_LABEL_ARGUMENT_NAME;
use super::sort_arguments;

/// Compare sorted input values, which means specifically establishing an order between the variants
/// of input values, and comparing values for the same variants accordingly.
///
/// Note that Floats and Ints are compared textually and not parsed numerically. This is fine for
/// the purposes of hashing.
fn compare_sorted_value(left: &executable::Value, right: &executable::Value) -> std::cmp::Ordering {
    use apollo_compiler::executable::Value;
    /// Returns an arbitrary index for each value type so values of different types are sorted consistently.
    fn discriminant(value: &Value) -> u8 {
        match value {
            Value::Null => 0,
            Value::Enum(_) => 1,
            Value::Variable(_) => 2,
            Value::String(_) => 3,
            Value::Float(_) => 4,
            Value::Int(_) => 5,
            Value::Boolean(_) => 6,
            Value::List(_) => 7,
            Value::Object(_) => 8,
        }
    }
    match (left, right) {
        (Value::Null, Value::Null) => std::cmp::Ordering::Equal,
        (Value::Enum(left), Value::Enum(right)) => left.cmp(right),
        (Value::Variable(left), Value::Variable(right)) => left.cmp(right),
        (Value::String(left), Value::String(right)) => left.cmp(right),
        (Value::Float(left), Value::Float(right)) => left.as_str().cmp(right.as_str()),
        (Value::Int(left), Value::Int(right)) => left.as_str().cmp(right.as_str()),
        (Value::Boolean(left), Value::Boolean(right)) => left.cmp(right),
        (Value::List(left), Value::List(right)) => left.len().cmp(&right.len()).then_with(|| {
            left.iter()
                .zip(right)
                .map(|(left, right)| compare_sorted_value(left, right))
                .find(|o| o.is_ne())
                .unwrap_or(std::cmp::Ordering::Equal)
        }),
        (Value::Object(left), Value::Object(right)) => compare_sorted_name_value_pairs(
            left.iter().map(|pair| &pair.0),
            left.iter().map(|pair| &pair.1),
            right.iter().map(|pair| &pair.0),
            right.iter().map(|pair| &pair.1),
        ),
        _ => discriminant(left).cmp(&discriminant(right)),
    }
}

/// Compare the (name, value) pair iterators, which are assumed to be sorted by name and have sorted
/// values. This is used for hashing objects/arguments in a way consistent with [same_directives()].
///
/// Note that pair iterators are compared by length, then lexicographically by name, then finally
/// recursively by value. This is intended to compute an ordering quickly for hashing.
fn compare_sorted_name_value_pairs<'doc>(
    left_names: impl ExactSizeIterator<Item = &'doc Name>,
    left_values: impl ExactSizeIterator<Item = &'doc Node<executable::Value>>,
    right_names: impl ExactSizeIterator<Item = &'doc Name>,
    right_values: impl ExactSizeIterator<Item = &'doc Node<executable::Value>>,
) -> std::cmp::Ordering {
    left_names
        .len()
        .cmp(&right_names.len())
        .then_with(|| left_names.cmp(right_names))
        .then_with(|| {
            left_values
                .zip(right_values)
                .map(|(left, right)| compare_sorted_value(left, right))
                .find(|o| o.is_ne())
                .unwrap_or(std::cmp::Ordering::Equal)
        })
}

/// Compare sorted arguments; see [compare_sorted_name_value_pairs()] for semantics. This is used
/// for hashing directives in a way consistent with [same_directives()].
fn compare_sorted_arguments(
    left: &[Node<executable::Argument>],
    right: &[Node<executable::Argument>],
) -> std::cmp::Ordering {
    compare_sorted_name_value_pairs(
        left.iter().map(|arg| &arg.name),
        left.iter().map(|arg| &arg.value),
        right.iter().map(|arg| &arg.name),
        right.iter().map(|arg| &arg.value),
    )
}

/// An empty apollo-compiler directive list that we can return a reference to when a
/// [`DirectiveList`] is in the empty state.
static EMPTY_DIRECTIVE_LIST: executable::DirectiveList = executable::DirectiveList(vec![]);

/// Contents for a non-empty directive list.
// NOTE: For serialization, we skip everything but the directives. This will require manually
// implementing `Deserialize` as all other fields are derived from the directives. This could also
// mean flattening the serialization and making this type deserialize from
// `executable::DirectiveList` directly.
#[derive(Debug, Clone, Serialize)]
struct DirectiveListInner {
    // Cached hash: hashing may be expensive with deeply nested values or very many directives,
    // so we only want to do it once.
    // The hash is eagerly precomputed because we expect to, most of the time, hash a DirectiveList
    // at least once (when inserting its selection into a selection map).
    #[serde(skip)]
    hash: u64,
    // Mutable access to the underlying directive list should not be handed out because `sort_order`
    // may get out of sync.
    #[serde(serialize_with = "crate::utils::serde_bridge::serialize_exe_directive_list")]
    directives: executable::DirectiveList,
    #[serde(skip)]
    sort_order: Vec<usize>,
}

impl PartialEq for DirectiveListInner {
    fn eq(&self, other: &Self) -> bool {
        self.hash == other.hash
            && self
                .iter_sorted()
                .zip(other.iter_sorted())
                .all(|(left, right)| {
                    // We can just use `Eq` because the arguments are sorted recursively
                    left.name == right.name && left.arguments == right.arguments
                })
    }
}

impl Eq for DirectiveListInner {}

impl DirectiveListInner {
    fn rehash(&mut self) {
        static SHARED_RANDOM: OnceLock<std::hash::RandomState> = OnceLock::new();

        let mut state = SHARED_RANDOM.get_or_init(Default::default).build_hasher();
        self.len().hash(&mut state);
        // Hash in sorted order
        for d in self.iter_sorted() {
            d.hash(&mut state);
        }
        self.hash = state.finish();
    }

    fn len(&self) -> usize {
        self.directives.len()
    }

    fn iter_sorted(&self) -> DirectiveIterSorted<'_> {
        DirectiveIterSorted {
            directives: &self.directives.0,
            inner: self.sort_order.iter(),
        }
    }
}

/// A list of directives, with order-independent hashing and equality.
///
/// Original order of directive applications is stored but is not part of hashing,
/// so it may not be maintained exactly when round-tripping several directive lists
/// through a HashSet for example.
///
/// Arguments and input object values provided to directives are all sorted and the
/// original order is not tracked.
///
/// This list is cheaply cloneable, but not intended for frequent mutations.
/// When the list is empty, it does not require an allocation.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
pub(crate) struct DirectiveList {
    inner: Option<Arc<DirectiveListInner>>,
}

impl Deref for DirectiveList {
    type Target = executable::DirectiveList;
    fn deref(&self) -> &Self::Target {
        self.inner
            .as_ref()
            .map_or(&EMPTY_DIRECTIVE_LIST, |inner| &inner.directives)
    }
}

impl Hash for DirectiveList {
    fn hash<H: Hasher>(&self, state: &mut H) {
        state.write_u64(self.inner.as_ref().map_or(0, |inner| inner.hash))
    }
}

impl Display for DirectiveList {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(inner) = &self.inner {
            inner.directives.fmt(f)
        } else {
            Ok(())
        }
    }
}

impl From<executable::DirectiveList> for DirectiveList {
    fn from(mut directives: executable::DirectiveList) -> Self {
        if directives.is_empty() {
            return Self::new();
        }

        // Sort directives, which means specifically sorting their arguments, sorting the directives by
        // name, and then breaking directive-name ties by comparing sorted arguments. This is used for
        // hashing arguments in a way consistent with [same_directives()].

        for directive in directives.iter_mut() {
            sort_arguments(&mut directive.make_mut().arguments);
        }

        let mut sort_order = (0usize..directives.len()).collect::<Vec<_>>();
        sort_order.sort_by(|left, right| {
            let left = &directives[*left];
            let right = &directives[*right];
            left.name
                .cmp(&right.name)
                .then_with(|| compare_sorted_arguments(&left.arguments, &right.arguments))
        });

        let mut partially_initialized = DirectiveListInner {
            hash: 0,
            directives,
            sort_order,
        };
        partially_initialized.rehash();
        Self {
            inner: Some(Arc::new(partially_initialized)),
        }
    }
}

impl FromIterator<Node<executable::Directive>> for DirectiveList {
    fn from_iter<T: IntoIterator<Item = Node<executable::Directive>>>(iter: T) -> Self {
        Self::from(executable::DirectiveList::from_iter(iter))
    }
}

impl FromIterator<executable::Directive> for DirectiveList {
    fn from_iter<T: IntoIterator<Item = executable::Directive>>(iter: T) -> Self {
        Self::from(executable::DirectiveList::from_iter(iter))
    }
}

impl DirectiveList {
    /// Create an empty directive list.
    pub(crate) const fn new() -> Self {
        Self { inner: None }
    }

    /// Create a directive list with a single directive.
    ///
    /// This sorts arguments and input object values provided to the directive.
    pub(crate) fn one(directive: impl Into<Node<executable::Directive>>) -> Self {
        std::iter::once(directive.into()).collect()
    }

    #[cfg(test)]
    pub(crate) fn parse(input: &str) -> Self {
        use apollo_compiler::ast;
        let input = format!(
            r#"query {{ field
# Directive input:
{input}
#
}}"#
        );
        let mut parser = apollo_compiler::parser::Parser::new();
        let document = parser
            .parse_ast(&input, "DirectiveList::parse.graphql")
            .unwrap();
        let Some(ast::Definition::OperationDefinition(operation)) = document.definitions.first()
        else {
            unreachable!();
        };
        let Some(ast::Selection::Field(field)) = operation.selection_set.first() else {
            unreachable!();
        };
        field.directives.clone().into()
    }

    /// Iterate the directives in their original order.
    pub(crate) fn iter(&self) -> impl ExactSizeIterator<Item = &Node<executable::Directive>> {
        self.inner
            .as_ref()
            .map_or(&EMPTY_DIRECTIVE_LIST, |inner| &inner.directives)
            .iter()
    }

    /// Remove one directive application by name.
    ///
    /// To remove a repeatable directive, you may need to call this multiple times.
    pub(crate) fn remove_one(&mut self, name: &str) -> Option<Node<executable::Directive>> {
        let Some(inner) = self.inner.as_mut() else {
            // Nothing to do on an empty list
            return None;
        };
        let index = inner.directives.iter().position(|dir| dir.name == name)?;

        // The directive exists and is the only directive: switch to the empty representation
        if inner.len() == 1 {
            // The index is guaranteed to exist so we can safely use the panicky [] syntax.
            let item = inner.directives[index].clone();
            self.inner = None;
            return Some(item);
        }

        // The directive exists: clone the inner structure if necessary.
        let inner = Arc::make_mut(inner);
        let sort_index = inner
            .sort_order
            .iter()
            .position(|sorted| *sorted == index)
            .expect("index must exist in sort order");
        let item = inner.directives.remove(index);
        inner.sort_order.remove(sort_index);

        for order in &mut inner.sort_order {
            if *order > index {
                *order -= 1;
            }
        }
        inner.rehash();
        Some(item)
    }

    /// Removes @defer directive from self if it has a matching label.
    pub(crate) fn remove_defer(&mut self, defer_labels: &IndexSet<String>) {
        let label = self
            .get(&DEFER_DIRECTIVE_NAME)
            .and_then(|directive| directive.specified_argument_by_name(&DEFER_LABEL_ARGUMENT_NAME))
            .and_then(|arg| arg.as_str());

        if label.is_some_and(|label| defer_labels.contains(label)) {
            self.remove_one(&DEFER_DIRECTIVE_NAME);
        }
    }
}

/// Iterate over a [`DirectiveList`] in a consistent sort order.
struct DirectiveIterSorted<'a> {
    directives: &'a [Node<executable::Directive>],
    inner: std::slice::Iter<'a, usize>,
}
impl<'a> Iterator for DirectiveIterSorted<'a> {
    type Item = &'a Node<executable::Directive>;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|index| &self.directives[*index])
    }
}

impl ExactSizeIterator for DirectiveIterSorted<'_> {
    fn len(&self) -> usize {
        self.inner.len()
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashSet;

    use super::*;

    #[test]
    fn consistent_hash() {
        let mut set = HashSet::new();

        assert!(set.insert(DirectiveList::new()));
        assert!(!set.insert(DirectiveList::new()));

        assert!(set.insert(DirectiveList::parse("@a @b")));
        assert!(!set.insert(DirectiveList::parse("@b @a")));
    }

    #[test]
    fn order_independent_equality() {
        assert_eq!(DirectiveList::new(), DirectiveList::new());
        assert_eq!(
            DirectiveList::parse("@a @b"),
            DirectiveList::parse("@b @a"),
            "equality should be order independent"
        );

        assert_eq!(
            DirectiveList::parse("@a(arg1: true, arg2: false) @b(arg2: false, arg1: true)"),
            DirectiveList::parse("@b(arg1: true, arg2: false) @a(arg1: true, arg2: false)"),
            "arguments should be order independent"
        );

        assert_eq!(
            DirectiveList::parse("@nested(object: { a: 1, b: 2, c: 3 })"),
            DirectiveList::parse("@nested(object: { b: 2, c: 3, a: 1 })"),
            "input objects should be order independent"
        );

        assert_eq!(
            DirectiveList::parse("@nested(object: [true, { a: 1, b: 2, c: { a: 3 } }])"),
            DirectiveList::parse("@nested(object: [true, { b: 2, c: { a: 3 }, a: 1 }])"),
            "input objects should be order independent"
        );
    }
}