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
use bytes::Bytes;
use derivative::Derivative;
use serde::de::DeserializeSeed;
use serde::de::Error;
use serde::Deserialize;
use serde::Serialize;
use serde_json_bytes::ByteString;
use serde_json_bytes::Map as JsonMap;
use serde_json_bytes::Value;

use crate::configuration::BatchingMode;
use crate::json_ext::Object;

/// A GraphQL `Request` used to represent both supergraph and subgraph requests.
#[derive(Clone, Derivative, Serialize, Deserialize, Default)]
// Note: if adding #[serde(deny_unknown_fields)],
// also remove `Fields::Other` in `DeserializeSeed` impl.
#[serde(rename_all = "camelCase")]
#[derivative(Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Request {
    /// The GraphQL operation (e.g., query, mutation) string.
    ///
    /// For historical purposes, the term "query" is commonly used to refer to
    /// *any* GraphQL operation which might be, e.g., a `mutation`.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub query: Option<String>,

    /// The (optional) GraphQL operation name.
    ///
    /// When specified, this name must match the name of an operation in the
    /// GraphQL document.  When excluded, there must exist only a single
    /// operation in the GraphQL document.  Typically, this value is provided as
    /// the `operationName` on an HTTP-sourced GraphQL request.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub operation_name: Option<String>,

    /// The (optional) GraphQL variables in the form of a JSON object.
    ///
    /// When specified, these variables can be referred to in the `query` by
    /// using `$variableName` syntax, where `{"variableName": "value"}` has been
    /// specified as this `variables` value.
    #[serde(
        skip_serializing_if = "Object::is_empty",
        default,
        deserialize_with = "deserialize_null_default"
    )]
    pub variables: Object,

    /// The (optional) GraphQL `extensions` of a GraphQL request.
    ///
    /// The implementations of extensions are server specific and not specified by
    /// the GraphQL specification.
    /// For example, Apollo projects support [Automated Persisted Queries][APQ]
    /// which are specified in the `extensions` of a request by populating the
    /// `persistedQuery` key within the `extensions` object:
    ///
    /// ```json
    /// {
    ///   "query": "...",
    ///   "variables": { /* ... */ },
    ///   "extensions": {
    ///     "persistedQuery": {
    ///       "version": 1,
    ///       "sha256Hash": "sha256HashOfQuery"
    /// .   }
    ///   }
    /// }
    /// ```
    ///
    /// [APQ]: https://www.apollographql.com/docs/apollo-server/performance/apq/
    #[serde(skip_serializing_if = "Object::is_empty", default)]
    pub extensions: Object,
}

// NOTE: this deserialize helper is used to transform `null` to Default::default()
fn deserialize_null_default<'de, D, T: Default + Deserialize<'de>>(
    deserializer: D,
) -> Result<T, D::Error>
where
    D: serde::Deserializer<'de>,
{
    <Option<T>>::deserialize(deserializer).map(|x| x.unwrap_or_default())
}

fn as_object<E: Error>(value: Value, null_is_default: bool) -> Result<Object, E> {
    use serde::de::Unexpected;

    let exp = if null_is_default {
        "a map or null"
    } else {
        "a map"
    };
    match value {
        Value::Object(object) => Ok(object),
        // Similar to `deserialize_null_default`:
        Value::Null if null_is_default => Ok(Object::default()),
        Value::Null => Err(E::invalid_type(Unexpected::Unit, &exp)),
        Value::Bool(value) => Err(E::invalid_type(Unexpected::Bool(value), &exp)),
        Value::Number(_) => Err(E::invalid_type(Unexpected::Other("a number"), &exp)),
        Value::String(value) => Err(E::invalid_type(Unexpected::Str(value.as_str()), &exp)),
        Value::Array(_) => Err(E::invalid_type(Unexpected::Seq, &exp)),
    }
}

#[buildstructor::buildstructor]
impl Request {
    #[builder(visibility = "pub")]
    /// This is the constructor (or builder) to use when constructing a GraphQL
    /// `Request`.
    ///
    /// The optionality of parameters on this constructor match the runtime
    /// requirements which are necessary to create a valid GraphQL `Request`.
    /// (This contrasts against the `fake_new` constructor which may be more
    /// tolerant to missing properties which are only necessary for testing
    /// purposes.  If you are writing tests, you may want to use `Self::fake_new()`.)
    fn new(
        query: Option<String>,
        operation_name: Option<String>,
        // Skip the `Object` type alias in order to use buildstructor’s map special-casing
        variables: JsonMap<ByteString, Value>,
        extensions: JsonMap<ByteString, Value>,
    ) -> Self {
        Self {
            query,
            operation_name,
            variables,
            extensions,
        }
    }

    #[builder(visibility = "pub")]
    /// This is the constructor (or builder) to use when constructing a **fake**
    /// GraphQL `Request`.  Use `Self::new()` to construct a _real_ request.
    ///
    /// This is offered for testing purposes and it relaxes the requirements
    /// of some parameters to be specified that would be otherwise required
    /// for a real request.  It's usually enough for most testing purposes,
    /// especially when a fully constructed `Request` is difficult to construct.
    /// While today, its paramters have the same optionality as its `new`
    /// counterpart, that may change in future versions.
    fn fake_new(
        query: Option<String>,
        operation_name: Option<String>,
        // Skip the `Object` type alias in order to use buildstructor’s map special-casing
        variables: JsonMap<ByteString, Value>,
        extensions: JsonMap<ByteString, Value>,
    ) -> Self {
        Self {
            query,
            operation_name,
            variables,
            extensions,
        }
    }

    /// Deserialize as JSON from `&Bytes`, avoiding string copies where possible
    pub fn deserialize_from_bytes(data: &Bytes) -> Result<Self, serde_json::Error> {
        let seed = RequestFromBytesSeed(data);
        let mut de = serde_json::Deserializer::from_slice(data);
        seed.deserialize(&mut de)
    }

    /// Convert encoded URL query string parameters (also known as "search
    /// params") into a GraphQL [`Request`].
    ///
    /// An error will be produced in the event that the query string parameters
    /// cannot be turned into a valid GraphQL `Request`.
    pub(crate) fn batch_from_urlencoded_query(
        url_encoded_query: String,
    ) -> Result<Vec<Request>, serde_json::Error> {
        let value: serde_json::Value = serde_urlencoded::from_bytes(url_encoded_query.as_bytes())
            .map_err(serde_json::Error::custom)?;

        Request::process_query_values(&value)
    }

    /// Convert Bytes into a GraphQL [`Request`].
    ///
    /// An error will be produced in the event that the query string parameters
    /// cannot be turned into a valid GraphQL `Request`.
    pub(crate) fn batch_from_bytes(bytes: &[u8]) -> Result<Vec<Request>, serde_json::Error> {
        let value: serde_json::Value =
            serde_json::from_slice(bytes).map_err(serde_json::Error::custom)?;

        Request::process_batch_values(&value)
    }

    fn allocate_result_array(value: &serde_json::Value) -> Vec<Request> {
        match value.as_array() {
            Some(array) => Vec::with_capacity(array.len()),
            None => Vec::with_capacity(1),
        }
    }

    fn process_batch_values(value: &serde_json::Value) -> Result<Vec<Request>, serde_json::Error> {
        let mut result = Request::allocate_result_array(value);

        if value.is_array() {
            tracing::info!(
                histogram.apollo_router.operations.batching.size = result.len() as f64,
                mode = %BatchingMode::BatchHttpLink // Only supported mode right now
            );

            tracing::info!(
                monotonic_counter.apollo_router.operations.batching = 1u64,
                mode = %BatchingMode::BatchHttpLink // Only supported mode right now
            );
            for entry in value
                .as_array()
                .expect("We already checked that it was an array")
            {
                let bytes = serde_json::to_vec(entry)?;
                result.push(Request::deserialize_from_bytes(&bytes.into())?);
            }
        } else {
            let bytes = serde_json::to_vec(value)?;
            result.push(Request::deserialize_from_bytes(&bytes.into())?);
        }
        Ok(result)
    }

    fn process_query_values(value: &serde_json::Value) -> Result<Vec<Request>, serde_json::Error> {
        let mut result = Request::allocate_result_array(value);

        if value.is_array() {
            tracing::info!(
                histogram.apollo_router.operations.batching.size = result.len() as f64,
                mode = "batch_http_link" // Only supported mode right now
            );

            tracing::info!(
                monotonic_counter.apollo_router.operations.batching = 1u64,
                mode = "batch_http_link" // Only supported mode right now
            );
            for entry in value
                .as_array()
                .expect("We already checked that it was an array")
            {
                result.push(Request::process_value(entry)?);
            }
        } else {
            result.push(Request::process_value(value)?)
        }
        Ok(result)
    }

    fn process_value(value: &serde_json::Value) -> Result<Request, serde_json::Error> {
        let operation_name =
            if let Some(serde_json::Value::String(operation_name)) = value.get("operationName") {
                Some(operation_name.clone())
            } else {
                None
            };

        let query = if let Some(serde_json::Value::String(query)) = value.get("query") {
            Some(query.as_str())
        } else {
            None
        };
        let variables: Object = get_from_urlencoded_value(value, "variables")?.unwrap_or_default();
        let extensions: Object =
            get_from_urlencoded_value(value, "extensions")?.unwrap_or_default();

        let request_builder = Self::builder()
            .variables(variables)
            .and_operation_name(operation_name)
            .extensions(extensions);

        let request = if let Some(query_str) = query {
            request_builder.query(query_str).build()
        } else {
            request_builder.build()
        };

        Ok(request)
    }

    /// Convert encoded URL query string parameters (also known as "search
    /// params") into a GraphQL [`Request`].
    ///
    /// An error will be produced in the event that the query string parameters
    /// cannot be turned into a valid GraphQL `Request`.
    pub fn from_urlencoded_query(url_encoded_query: String) -> Result<Request, serde_json::Error> {
        let urldecoded: serde_json::Value =
            serde_urlencoded::from_bytes(url_encoded_query.as_bytes())
                .map_err(serde_json::Error::custom)?;

        Request::process_value(&urldecoded)
    }
}

fn get_from_urlencoded_value<'a, T: Deserialize<'a>>(
    object: &'a serde_json::Value,
    key: &str,
) -> Result<Option<T>, serde_json::Error> {
    if let Some(serde_json::Value::String(byte_string)) = object.get(key) {
        Some(serde_json::from_str(byte_string.as_str())).transpose()
    } else {
        Ok(None)
    }
}

struct RequestFromBytesSeed<'data>(&'data Bytes);

impl<'data, 'de> DeserializeSeed<'de> for RequestFromBytesSeed<'data> {
    type Value = Request;

    fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(serde::Deserialize)]
        #[serde(field_identifier, rename_all = "camelCase")]
        enum Field {
            Query,
            OperationName,
            Variables,
            Extensions,
            #[serde(other)]
            Other,
        }

        const FIELDS: &[&str] = &["query", "operationName", "variables", "extensions"];

        struct RequestVisitor<'data>(&'data Bytes);

        impl<'data, 'de> serde::de::Visitor<'de> for RequestVisitor<'data> {
            type Value = Request;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("a GraphQL request")
            }

            fn visit_map<V>(self, mut map: V) -> Result<Request, V::Error>
            where
                V: serde::de::MapAccess<'de>,
            {
                let mut query = None;
                let mut operation_name = None;
                let mut variables = None;
                let mut extensions = None;
                while let Some(key) = map.next_key()? {
                    match key {
                        Field::Query => {
                            if query.is_some() {
                                return Err(Error::duplicate_field("query"));
                            }
                            query = Some(map.next_value()?);
                        }
                        Field::OperationName => {
                            if operation_name.is_some() {
                                return Err(Error::duplicate_field("operationName"));
                            }
                            operation_name = Some(map.next_value()?);
                        }
                        Field::Variables => {
                            if variables.is_some() {
                                return Err(Error::duplicate_field("variables"));
                            }
                            let seed = serde_json_bytes::value::BytesSeed::new(self.0);
                            let value = map.next_value_seed(seed)?;
                            let null_is_default = true;
                            variables = Some(as_object(value, null_is_default)?);
                        }
                        Field::Extensions => {
                            if extensions.is_some() {
                                return Err(Error::duplicate_field("extensions"));
                            }
                            let seed = serde_json_bytes::value::BytesSeed::new(self.0);
                            let value = map.next_value_seed(seed)?;
                            let null_is_default = false;
                            extensions = Some(as_object(value, null_is_default)?);
                        }
                        Field::Other => {
                            let _: serde::de::IgnoredAny = map.next_value()?;
                        }
                    }
                }
                Ok(Request {
                    query: query.unwrap_or_default(),
                    operation_name: operation_name.unwrap_or_default(),
                    variables: variables.unwrap_or_default(),
                    extensions: extensions.unwrap_or_default(),
                })
            }
        }

        deserializer.deserialize_struct("Request", FIELDS, RequestVisitor(self.0))
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;
    use serde_json_bytes::json as bjson;
    use test_log::test;

    use super::*;

    #[test]
    fn test_request() {
        let data = json!(
        {
          "query": "query aTest($arg1: String!) { test(who: $arg1) }",
          "operationName": "aTest",
          "variables": { "arg1": "me" },
          "extensions": {"extension": 1}
        })
        .to_string();
        println!("data: {data}");
        let result = serde_json::from_str::<Request>(data.as_str());
        println!("result: {result:?}");
        assert_eq!(
            result.unwrap(),
            Request::builder()
                .query("query aTest($arg1: String!) { test(who: $arg1) }".to_owned())
                .operation_name("aTest")
                .variables(bjson!({ "arg1": "me" }).as_object().unwrap().clone())
                .extensions(bjson!({"extension": 1}).as_object().cloned().unwrap())
                .build()
        );
    }

    #[test]
    fn test_no_variables() {
        let result = serde_json::from_str::<Request>(
            json!(
            {
              "query": "query aTest($arg1: String!) { test(who: $arg1) }",
              "operationName": "aTest",
              "extensions": {"extension": 1}
            })
            .to_string()
            .as_str(),
        );
        assert_eq!(
            result.unwrap(),
            Request::builder()
                .query("query aTest($arg1: String!) { test(who: $arg1) }".to_owned())
                .operation_name("aTest")
                .extensions(bjson!({"extension": 1}).as_object().cloned().unwrap())
                .build()
        );
    }

    #[test]
    // rover sends { "variables": null } when running the introspection query,
    // and possibly running other queries as well.
    fn test_variables_is_null() {
        let result = serde_json::from_str::<Request>(
            json!(
            {
              "query": "query aTest($arg1: String!) { test(who: $arg1) }",
              "operationName": "aTest",
              "variables": null,
              "extensions": {"extension": 1}
            })
            .to_string()
            .as_str(),
        );
        assert_eq!(
            result.unwrap(),
            Request::builder()
                .query("query aTest($arg1: String!) { test(who: $arg1) }")
                .operation_name("aTest")
                .extensions(bjson!({"extension": 1}).as_object().cloned().unwrap())
                .build()
        );
    }

    #[test]
    fn from_urlencoded_query_works() {
        let query_string = "query=%7B+topProducts+%7B+upc+name+reviews+%7B+id+product+%7B+name+%7D+author+%7B+id+name+%7D+%7D+%7D+%7D&extensions=%7B+%22persistedQuery%22+%3A+%7B+%22version%22+%3A+1%2C+%22sha256Hash%22+%3A+%2220a101de18d4a9331bfc4ccdfef33cc735876a689490433570f17bdd4c0bad3f%22+%7D+%7D".to_string();

        let expected_result = serde_json::from_str::<Request>(
            json!(
            {
              "query": "{ topProducts { upc name reviews { id product { name } author { id name } } } }",
              "extensions": {
                  "persistedQuery": {
                      "version": 1,
                      "sha256Hash": "20a101de18d4a9331bfc4ccdfef33cc735876a689490433570f17bdd4c0bad3f"
                  }
                }
            })
            .to_string()
            .as_str(),
        ).unwrap();

        let req = Request::from_urlencoded_query(query_string).unwrap();

        assert_eq!(expected_result, req);
    }

    #[test]
    fn from_urlencoded_query_with_variables_works() {
        let query_string = "query=%7B+topProducts+%7B+upc+name+reviews+%7B+id+product+%7B+name+%7D+author+%7B+id+name+%7D+%7D+%7D+%7D&variables=%7B%22date%22%3A%222022-01-01T00%3A00%3A00%2B00%3A00%22%7D&extensions=%7B+%22persistedQuery%22+%3A+%7B+%22version%22+%3A+1%2C+%22sha256Hash%22+%3A+%2220a101de18d4a9331bfc4ccdfef33cc735876a689490433570f17bdd4c0bad3f%22+%7D+%7D".to_string();

        let expected_result = serde_json::from_str::<Request>(
            json!(
            {
              "query": "{ topProducts { upc name reviews { id product { name } author { id name } } } }",
              "variables": {"date": "2022-01-01T00:00:00+00:00"},
              "extensions": {
                  "persistedQuery": {
                      "version": 1,
                      "sha256Hash": "20a101de18d4a9331bfc4ccdfef33cc735876a689490433570f17bdd4c0bad3f"
                  }
                }
            })
            .to_string()
            .as_str(),
        ).unwrap();

        let req = Request::from_urlencoded_query(query_string).unwrap();

        assert_eq!(expected_result, req);
    }
}