-
Notifications
You must be signed in to change notification settings - Fork 244
/
response.rs
491 lines (456 loc) 路 15.8 KB
/
response.rs
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
#![allow(missing_docs)] // FIXME
use std::time::Instant;
use bytes::Bytes;
use serde::Deserialize;
use serde::Serialize;
use serde_json_bytes::ByteString;
use serde_json_bytes::Map;
use crate::error::Error;
use crate::error::FetchError;
use crate::json_ext::Object;
use crate::json_ext::Path;
use crate::json_ext::Value;
/// A graphql primary response.
/// Used for federated and subgraph queries.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Response {
/// The label that was passed to the defer or stream directive for this patch.
#[serde(skip_serializing_if = "Option::is_none", default)]
pub label: Option<String>,
/// The optional graphql errors encountered.
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub errors: Vec<Error>,
/// The response data.
#[serde(skip_serializing_if = "Option::is_none", default)]
pub data: Option<Value>,
/// The path that the data should be merged at.
#[serde(skip_serializing_if = "Option::is_none", default)]
pub path: Option<Path>,
/// The optional graphql extensions.
#[serde(skip_serializing_if = "Object::is_empty", default)]
pub extensions: Object,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub has_next: Option<bool>,
#[serde(skip, default)]
pub subscribed: Option<bool>,
/// Used for subscription event to compute the duration of a subscription event
#[serde(skip, default)]
pub created_at: Option<Instant>,
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub incremental: Vec<IncrementalResponse>,
}
#[buildstructor::buildstructor]
impl Response {
/// Constructor
#[builder(visibility = "pub")]
#[allow(clippy::too_many_arguments)]
fn new(
label: Option<String>,
data: Option<Value>,
path: Option<Path>,
errors: Vec<Error>,
extensions: Map<ByteString, Value>,
_subselection: Option<String>,
has_next: Option<bool>,
subscribed: Option<bool>,
incremental: Vec<IncrementalResponse>,
created_at: Option<Instant>,
) -> Self {
Self {
label,
data,
path,
errors,
extensions,
has_next,
subscribed,
incremental,
created_at,
}
}
/// If path is None, this is a primary response.
pub fn is_primary(&self) -> bool {
self.path.is_none()
}
/// append_errors default the errors `path` with the one provided.
pub fn append_errors(&mut self, errors: &mut Vec<Error>) {
self.errors.append(errors)
}
/// Create a [`Response`] from the supplied [`Bytes`].
///
/// This will return an error (identifying the faulty service) if the input is invalid.
pub(crate) fn from_bytes(service_name: &str, b: Bytes) -> Result<Response, FetchError> {
let value =
Value::from_bytes(b).map_err(|error| FetchError::SubrequestMalformedResponse {
service: service_name.to_string(),
reason: error.to_string(),
})?;
let mut object =
ensure_object!(value).map_err(|error| FetchError::SubrequestMalformedResponse {
service: service_name.to_string(),
reason: error.to_string(),
})?;
let data = object.remove("data");
let errors = extract_key_value_from_object!(object, "errors", Value::Array(v) => v)
.map_err(|err| FetchError::SubrequestMalformedResponse {
service: service_name.to_string(),
reason: err.to_string(),
})?
.into_iter()
.flatten()
.map(|v| Error::from_value(service_name, v))
.collect::<Result<Vec<Error>, FetchError>>()?;
let extensions =
extract_key_value_from_object!(object, "extensions", Value::Object(o) => o)
.map_err(|err| FetchError::SubrequestMalformedResponse {
service: service_name.to_string(),
reason: err.to_string(),
})?
.unwrap_or_default();
let label = extract_key_value_from_object!(object, "label", Value::String(s) => s)
.map_err(|err| FetchError::SubrequestMalformedResponse {
service: service_name.to_string(),
reason: err.to_string(),
})?
.map(|s| s.as_str().to_string());
let path = extract_key_value_from_object!(object, "path")
.map(serde_json_bytes::from_value)
.transpose()
.map_err(|err| FetchError::SubrequestMalformedResponse {
service: service_name.to_string(),
reason: err.to_string(),
})?;
let has_next = extract_key_value_from_object!(object, "hasNext", Value::Bool(b) => b)
.map_err(|err| FetchError::SubrequestMalformedResponse {
service: service_name.to_string(),
reason: err.to_string(),
})?;
let incremental =
extract_key_value_from_object!(object, "incremental", Value::Array(a) => a).map_err(
|err| FetchError::SubrequestMalformedResponse {
service: service_name.to_string(),
reason: err.to_string(),
},
)?;
let incremental: Vec<IncrementalResponse> = match incremental {
Some(v) => v
.into_iter()
.map(serde_json_bytes::from_value)
.collect::<Result<Vec<IncrementalResponse>, _>>()
.map_err(|err| FetchError::SubrequestMalformedResponse {
service: service_name.to_string(),
reason: err.to_string(),
})?,
None => vec![],
};
// Graphql spec says:
// If the data entry in the response is not present, the errors entry in the response must not be empty.
// It must contain at least one error. The errors it contains should indicate why no data was able to be returned.
if data.is_none() && errors.is_empty() {
return Err(FetchError::SubrequestMalformedResponse {
service: service_name.to_string(),
reason: "graphql response without data must contain at least one error".to_string(),
});
}
Ok(Response {
label,
data,
path,
errors,
extensions,
has_next,
subscribed: None,
incremental,
created_at: None,
})
}
}
/// A graphql incremental response.
/// Used with `@defer`
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct IncrementalResponse {
/// The label that was passed to the defer or stream directive for this patch.
#[serde(skip_serializing_if = "Option::is_none", default)]
pub label: Option<String>,
/// The response data.
#[serde(skip_serializing_if = "Option::is_none", default)]
pub data: Option<Value>,
/// The path that the data should be merged at.
#[serde(skip_serializing_if = "Option::is_none", default)]
pub path: Option<Path>,
/// The optional graphql errors encountered.
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub errors: Vec<Error>,
/// The optional graphql extensions.
#[serde(skip_serializing_if = "Object::is_empty", default)]
pub extensions: Object,
}
#[buildstructor::buildstructor]
impl IncrementalResponse {
/// Constructor
#[builder(visibility = "pub")]
fn new(
label: Option<String>,
data: Option<Value>,
path: Option<Path>,
errors: Vec<Error>,
extensions: Map<ByteString, Value>,
) -> Self {
Self {
label,
data,
path,
errors,
extensions,
}
}
/// append_errors default the errors `path` with the one provided.
pub fn append_errors(&mut self, errors: &mut Vec<Error>) {
self.errors.append(errors)
}
}
#[cfg(test)]
mod tests {
use router_bridge::planner::Location;
use serde_json::json;
use serde_json_bytes::json as bjson;
use super::*;
#[test]
fn test_append_errors_path_fallback_and_override() {
let expected_errors = vec![
Error {
message: "Something terrible happened!".to_string(),
path: Some(Path::from("here")),
..Default::default()
},
Error {
message: "I mean for real".to_string(),
..Default::default()
},
];
let mut errors_to_append = vec![
Error {
message: "Something terrible happened!".to_string(),
path: Some(Path::from("here")),
..Default::default()
},
Error {
message: "I mean for real".to_string(),
..Default::default()
},
];
let mut response = Response::builder().build();
response.append_errors(&mut errors_to_append);
assert_eq!(response.errors, expected_errors);
}
#[test]
fn test_response() {
let result = serde_json::from_str::<Response>(
json!(
{
"errors": [
{
"message": "Name for character with ID 1002 could not be fetched.",
"locations": [{ "line": 6, "column": 7 }],
"path": ["hero", "heroFriends", 1, "name"],
"extensions": {
"error-extension": 5,
}
}
],
"data": {
"hero": {
"name": "R2-D2",
"heroFriends": [
{
"id": "1000",
"name": "Luke Skywalker"
},
{
"id": "1002",
"name": null
},
{
"id": "1003",
"name": "Leia Organa"
}
]
}
},
"extensions": {
"response-extension": 3,
}
})
.to_string()
.as_str(),
);
assert_eq!(
result.unwrap(),
Response::builder()
.data(json!({
"hero": {
"name": "R2-D2",
"heroFriends": [
{
"id": "1000",
"name": "Luke Skywalker"
},
{
"id": "1002",
"name": null
},
{
"id": "1003",
"name": "Leia Organa"
}
]
}
}))
.errors(vec![Error {
message: "Name for character with ID 1002 could not be fetched.".into(),
locations: vec!(Location { line: 6, column: 7 }),
path: Some(Path::from("hero/heroFriends/1/name")),
extensions: bjson!({
"error-extension": 5,
})
.as_object()
.cloned()
.unwrap()
}])
.extensions(
bjson!({
"response-extension": 3,
})
.as_object()
.cloned()
.unwrap()
)
.build()
);
}
#[test]
fn test_patch_response() {
let result = serde_json::from_str::<Response>(
json!(
{
"label": "part",
"hasNext": true,
"path": ["hero", "heroFriends", 1, "name"],
"errors": [
{
"message": "Name for character with ID 1002 could not be fetched.",
"locations": [{ "line": 6, "column": 7 }],
"path": ["hero", "heroFriends", 1, "name"],
"extensions": {
"error-extension": 5,
}
}
],
"data": {
"hero": {
"name": "R2-D2",
"heroFriends": [
{
"id": "1000",
"name": "Luke Skywalker"
},
{
"id": "1002",
"name": null
},
{
"id": "1003",
"name": "Leia Organa"
}
]
}
},
"extensions": {
"response-extension": 3,
}
})
.to_string()
.as_str(),
);
assert_eq!(
result.unwrap(),
Response::builder()
.label("part".to_owned())
.data(json!({
"hero": {
"name": "R2-D2",
"heroFriends": [
{
"id": "1000",
"name": "Luke Skywalker"
},
{
"id": "1002",
"name": null
},
{
"id": "1003",
"name": "Leia Organa"
}
]
}
}))
.path(Path::from("hero/heroFriends/1/name"))
.errors(vec![Error {
message: "Name for character with ID 1002 could not be fetched.".into(),
locations: vec!(Location { line: 6, column: 7 }),
path: Some(Path::from("hero/heroFriends/1/name")),
extensions: bjson!({
"error-extension": 5,
})
.as_object()
.cloned()
.unwrap()
}])
.extensions(
bjson!({
"response-extension": 3,
})
.as_object()
.cloned()
.unwrap()
)
.has_next(true)
.build()
);
}
#[test]
fn test_no_data_and_no_errors() {
let response = Response::from_bytes("test", "{\"errors\":null}".into());
assert_eq!(
response.expect_err("no data and no errors"),
FetchError::SubrequestMalformedResponse {
service: "test".to_string(),
reason: "graphql response without data must contain at least one error".to_string(),
}
);
}
#[test]
fn test_errors_come_first() {
let response = Response::builder()
.error(
Error::builder()
.message("some random error")
.extension_code("RANDOM_ERROR")
.build(),
)
.data(json!({
"random": "data"
}))
.build();
let json = serde_json::to_string(&response).unwrap();
let errors_location = json.find(r#""errors":"#).unwrap();
let data_location = json.find(r#""data":"#).unwrap();
// Make sure that errors are present before data
assert!(errors_location < data_location)
}
}