-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy patherror.rs
More file actions
479 lines (444 loc) · 18.3 KB
/
error.rs
File metadata and controls
479 lines (444 loc) · 18.3 KB
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
use graphql_parser::Pos;
use hex::FromHexError;
use num_bigint;
use serde::ser::*;
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use std::string::FromUtf8Error;
use std::sync::Arc;
use crate::data::graphql::SerializableValue;
use crate::data::subgraph::*;
use crate::prelude::q;
use crate::{components::store::StoreError, prelude::CacheWeight};
#[derive(Debug)]
pub struct CloneableAnyhowError(Arc<anyhow::Error>);
impl Clone for CloneableAnyhowError {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl From<anyhow::Error> for CloneableAnyhowError {
fn from(f: anyhow::Error) -> Self {
Self(Arc::new(f))
}
}
/// Error caused while executing a [Query](struct.Query.html).
#[derive(Debug, Clone)]
pub enum QueryExecutionError {
OperationNameRequired,
OperationNotFound(String),
NotSupported(String),
NoRootSubscriptionObjectType,
NonNullError(Pos, String),
ListValueError(Pos, String),
NamedTypeError(String),
AbstractTypeError(String),
InvalidArgumentError(Pos, String, q::Value),
MissingArgumentError(Pos, String),
ValidationError(Option<Pos>, String),
InvalidVariableTypeError(Pos, String),
MissingVariableError(Pos, String),
ResolveEntitiesError(String),
OrderByNotSupportedError(String, String),
OrderByNotSupportedForType(String),
FilterNotSupportedError(String, String),
UnknownField(Pos, String, String),
EmptyQuery,
MultipleSubscriptionFields,
SubgraphDeploymentIdError(String),
RangeArgumentsError(&'static str, u32, i64),
InvalidFilterError,
EntityFieldError(String, String),
ListTypesError(String, Vec<String>),
ListFilterError(String),
ValueParseError(String, String),
AttributeTypeError(String, String),
EntityParseError(String),
StoreError(CloneableAnyhowError),
Timeout,
EmptySelectionSet(String),
AmbiguousDerivedFromResult(Pos, String, String, String),
Unimplemented(String),
EnumCoercionError(Pos, String, q::Value, String, Vec<String>),
ScalarCoercionError(Pos, String, q::Value, String),
TooComplex(u64, u64), // (complexity, max_complexity)
TooDeep(u8), // max_depth
CyclicalFragment(String),
TooExpensive,
Throttled,
UndefinedFragment(String),
// Using slow and prefetch query resolution yield different results
IncorrectPrefetchResult { slow: q::Value, prefetch: q::Value },
Panic(String),
EventStreamError,
FulltextQueryRequiresFilter,
FulltextQueryInvalidSyntax(String),
DeploymentReverted,
SubgraphManifestResolveError(Arc<SubgraphManifestResolveError>),
InvalidSubgraphManifest,
ResultTooBig(usize, usize),
}
impl QueryExecutionError {
pub fn is_attestable(&self) -> bool {
use self::QueryExecutionError::*;
match self {
OperationNameRequired
| OperationNotFound(_)
| NotSupported(_)
| NoRootSubscriptionObjectType
| NamedTypeError(_)
| AbstractTypeError(_)
| InvalidArgumentError(_, _, _)
| MissingArgumentError(_, _)
| InvalidVariableTypeError(_, _)
| MissingVariableError(_, _)
| OrderByNotSupportedError(_, _)
| OrderByNotSupportedForType(_)
| FilterNotSupportedError(_, _)
| UnknownField(_, _, _)
| EmptyQuery
| MultipleSubscriptionFields
| SubgraphDeploymentIdError(_)
| InvalidFilterError
| EntityFieldError(_, _)
| ListTypesError(_, _)
| ListFilterError(_)
| AttributeTypeError(_, _)
| EmptySelectionSet(_)
| Unimplemented(_)
| CyclicalFragment(_)
| UndefinedFragment(_)
| FulltextQueryInvalidSyntax(_)
| FulltextQueryRequiresFilter => true,
NonNullError(_, _)
| ListValueError(_, _)
| ResolveEntitiesError(_)
| RangeArgumentsError(_, _, _)
| ValueParseError(_, _)
| EntityParseError(_)
| StoreError(_)
| Timeout
| EnumCoercionError(_, _, _, _, _)
| ScalarCoercionError(_, _, _, _)
| AmbiguousDerivedFromResult(_, _, _, _)
| TooComplex(_, _)
| TooDeep(_)
| IncorrectPrefetchResult { .. }
| Panic(_)
| EventStreamError
| TooExpensive
| Throttled
| DeploymentReverted
| SubgraphManifestResolveError(_)
| InvalidSubgraphManifest
| ValidationError(_, _)
| ResultTooBig(_, _) => false,
}
}
}
impl Error for QueryExecutionError {
fn description(&self) -> &str {
"Query execution error"
}
fn cause(&self) -> Option<&dyn Error> {
None
}
}
impl fmt::Display for QueryExecutionError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::QueryExecutionError::*;
match self {
OperationNameRequired => write!(f, "Operation name required"),
OperationNotFound(s) => {
write!(f, "Operation name not found `{}`", s)
}
ValidationError(_pos, message) => {
write!(f, "{}", message)
}
NotSupported(s) => write!(f, "Not supported: {}", s),
NoRootSubscriptionObjectType => {
write!(f, "No root Subscription type defined in the schema")
}
NonNullError(_, s) => {
write!(f, "Null value resolved for non-null field `{}`", s)
}
ListValueError(_, s) => {
write!(f, "Non-list value resolved for list field `{}`", s)
}
NamedTypeError(s) => {
write!(f, "Failed to resolve named type `{}`", s)
}
AbstractTypeError(s) => {
write!(f, "Failed to resolve abstract type `{}`", s)
}
InvalidArgumentError(_, s, v) => {
write!(f, "Invalid value provided for argument `{}`: {:?}", s, v)
}
MissingArgumentError(_, s) => {
write!(f, "No value provided for required argument: `{}`", s)
}
InvalidVariableTypeError(_, s) => {
write!(f, "Variable `{}` must have an input type", s)
}
MissingVariableError(_, s) => {
write!(f, "No value provided for required variable `{}`", s)
}
ResolveEntitiesError(e) => {
write!(f, "Failed to get entities from store: {}", e)
}
OrderByNotSupportedError(entity, field) => {
write!(f, "Ordering by `{}` is not supported for type `{}`", field, entity)
}
OrderByNotSupportedForType(field_type) => {
write!(f, "Ordering by `{}` fields is not supported", field_type)
}
FilterNotSupportedError(value, filter) => {
write!(f, "Filter not supported by value `{}`: `{}`", value, filter)
}
UnknownField(_, t, s) => {
write!(f, "Type `{}` has no field `{}`", t, s)
}
EmptyQuery => write!(f, "The query is empty"),
MultipleSubscriptionFields => write!(
f,
"Only a single top-level field is allowed in subscriptions"
),
SubgraphDeploymentIdError(s) => {
write!(f, "Failed to get subgraph ID from type: `{}`", s)
}
RangeArgumentsError(arg, max, actual) => {
write!(f, "The `{}` argument must be between 0 and {}, but is {}", arg, max, actual)
}
InvalidFilterError => write!(f, "Filter must by an object"),
EntityFieldError(e, a) => {
write!(f, "Entity `{}` has no attribute `{}`", e, a)
}
ListTypesError(s, v) => write!(
f,
"Values passed to filter `{}` must be of the same type but are of different types: {}",
s,
v.join(", ")
),
ListFilterError(s) => {
write!(f, "Non-list value passed to `{}` filter", s)
}
ValueParseError(t, e) => {
write!(f, "Failed to decode `{}` value: `{}`", t, e)
}
AttributeTypeError(value, ty) => {
write!(f, "Query contains value with invalid type `{}`: `{}`", ty, value)
}
EntityParseError(s) => {
write!(f, "Broken entity found in store: {}", s)
}
StoreError(e) => {
write!(f, "Store error: {}", e.0)
}
Timeout => write!(f, "Query timed out"),
EmptySelectionSet(entity_type) => {
write!(f, "Selection set for type `{}` is empty", entity_type)
}
AmbiguousDerivedFromResult(_, field, target_type, target_field) => {
write!(f, "Ambiguous result for derived field `{}`: \
Multiple `{}` entities refer back via `{}`",
field, target_type, target_field)
}
Unimplemented(feature) => {
write!(f, "Feature `{}` is not yet implemented", feature)
}
EnumCoercionError(_, field, value, enum_type, values) => {
write!(f, "Failed to coerce value `{}` of field `{}` to enum type `{}`. Possible values are: {}", value, field, enum_type, values.join(", "))
}
ScalarCoercionError(_, field, value, scalar_type) => {
write!(f, "Failed to coerce value `{}` of field `{}` to scalar type `{}`", value, field, scalar_type)
}
TooComplex(complexity, max_complexity) => {
write!(f, "query potentially returns `{}` entities or more and thereby exceeds \
the limit of `{}` entities. Possible solutions are reducing the depth \
of the query, querying fewer relationships or using `first` to \
return smaller collections", complexity, max_complexity)
}
TooDeep(max_depth) => write!(f, "query has a depth that exceeds the limit of `{}`", max_depth),
CyclicalFragment(name) =>write!(f, "query has fragment cycle including `{}`", name),
UndefinedFragment(frag_name) => write!(f, "fragment `{}` is not defined", frag_name),
IncorrectPrefetchResult{ .. } => write!(f, "Running query with prefetch \
and slow query resolution yielded different results. \
This is a bug. Please open an issue at \
https://github.com/graphprotocol/graph-node"),
Panic(msg) => write!(f, "panic processing query: {}", msg),
EventStreamError => write!(f, "error in the subscription event stream"),
FulltextQueryRequiresFilter => write!(f, "fulltext search queries can only use EntityFilter::Equal"),
FulltextQueryInvalidSyntax(msg) => write!(f, "Invalid fulltext search query syntax. Error: {}. Hint: Search terms with spaces need to be enclosed in single quotes", msg),
TooExpensive => write!(f, "query is too expensive"),
Throttled => write!(f, "service is overloaded and can not run the query right now. Please try again in a few minutes"),
DeploymentReverted => write!(f, "the chain was reorganized while executing the query"),
SubgraphManifestResolveError(e) => write!(f, "failed to resolve subgraph manifest: {}", e),
InvalidSubgraphManifest => write!(f, "invalid subgraph manifest file"),
ResultTooBig(actual, limit) => write!(f, "the result size of {} is larger than the allowed limit of {}", actual, limit),
}
}
}
impl From<QueryExecutionError> for Vec<QueryExecutionError> {
fn from(e: QueryExecutionError) -> Self {
vec![e]
}
}
impl From<FromHexError> for QueryExecutionError {
fn from(e: FromHexError) -> Self {
QueryExecutionError::ValueParseError("Bytes".to_string(), e.to_string())
}
}
impl From<num_bigint::ParseBigIntError> for QueryExecutionError {
fn from(e: num_bigint::ParseBigIntError) -> Self {
QueryExecutionError::ValueParseError("BigInt".to_string(), format!("{}", e))
}
}
impl From<bigdecimal::ParseBigDecimalError> for QueryExecutionError {
fn from(e: bigdecimal::ParseBigDecimalError) -> Self {
QueryExecutionError::ValueParseError("BigDecimal".to_string(), format!("{}", e))
}
}
impl From<StoreError> for QueryExecutionError {
fn from(e: StoreError) -> Self {
QueryExecutionError::StoreError(CloneableAnyhowError(Arc::new(e.into())))
}
}
impl From<SubgraphManifestResolveError> for QueryExecutionError {
fn from(e: SubgraphManifestResolveError) -> Self {
QueryExecutionError::SubgraphManifestResolveError(Arc::new(e))
}
}
/// Error caused while processing a [Query](struct.Query.html) request.
#[derive(Clone, Debug)]
pub enum QueryError {
EncodingError(FromUtf8Error),
ParseError(Arc<anyhow::Error>),
ExecutionError(QueryExecutionError),
IndexingError,
}
impl QueryError {
pub fn is_attestable(&self) -> bool {
match self {
QueryError::EncodingError(_) | QueryError::ParseError(_) => true,
QueryError::ExecutionError(err) => err.is_attestable(),
QueryError::IndexingError => false,
}
}
}
impl From<FromUtf8Error> for QueryError {
fn from(e: FromUtf8Error) -> Self {
QueryError::EncodingError(e)
}
}
impl From<QueryExecutionError> for QueryError {
fn from(e: QueryExecutionError) -> Self {
QueryError::ExecutionError(e)
}
}
impl Error for QueryError {
fn description(&self) -> &str {
"Query error"
}
fn cause(&self) -> Option<&dyn Error> {
match *self {
QueryError::EncodingError(ref e) => Some(e),
QueryError::ExecutionError(ref e) => Some(e),
_ => None,
}
}
}
impl fmt::Display for QueryError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
QueryError::EncodingError(ref e) => write!(f, "{}", e),
QueryError::ExecutionError(ref e) => write!(f, "{}", e),
QueryError::ParseError(ref e) => write!(f, "{}", e),
// This error message is part of attestable responses.
QueryError::IndexingError => write!(f, "indexing_error"),
}
}
}
impl Serialize for QueryError {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
use self::QueryExecutionError::*;
let entry_count =
if let QueryError::ExecutionError(QueryExecutionError::IncorrectPrefetchResult {
..
}) = self
{
3
} else {
1
};
let mut map = serializer.serialize_map(Some(entry_count))?;
let msg = match self {
// Serialize parse errors with their location (line, column) to make it easier
// for users to find where the errors are; this is likely to change as the
// graphql_parser team makes improvements to their error reporting
QueryError::ParseError(_) => {
// Split the inner message into (first line, rest)
let msg = format!("{}", self);
let inner_msg = msg.replace("query parse error:", "");
let inner_msg = inner_msg.trim();
let parts: Vec<&str> = inner_msg.splitn(2, '\n').collect();
// Find the colon in the first line and split there
let colon_pos = parts[0].rfind(':').unwrap();
let (a, b) = parts[0].split_at(colon_pos);
// Find the line and column numbers and convert them to u32
let line: u32 = a
.matches(char::is_numeric)
.collect::<String>()
.parse()
.unwrap();
let column: u32 = b
.matches(char::is_numeric)
.collect::<String>()
.parse()
.unwrap();
// Generate the list of locations
let mut location = HashMap::new();
location.insert("line", line);
location.insert("column", column);
map.serialize_entry("locations", &vec![location])?;
// Only use the remainder after the location as the error message
parts[1].to_string()
}
// Serialize entity resolution errors using their position
QueryError::ExecutionError(NonNullError(pos, _))
| QueryError::ExecutionError(ListValueError(pos, _))
| QueryError::ExecutionError(InvalidArgumentError(pos, _, _))
| QueryError::ExecutionError(MissingArgumentError(pos, _))
| QueryError::ExecutionError(InvalidVariableTypeError(pos, _))
| QueryError::ExecutionError(MissingVariableError(pos, _))
| QueryError::ExecutionError(AmbiguousDerivedFromResult(pos, _, _, _))
| QueryError::ExecutionError(EnumCoercionError(pos, _, _, _, _))
| QueryError::ExecutionError(ScalarCoercionError(pos, _, _, _))
| QueryError::ExecutionError(UnknownField(pos, _, _)) => {
let mut location = HashMap::new();
location.insert("line", pos.line);
location.insert("column", pos.column);
map.serialize_entry("locations", &vec![location])?;
format!("{}", self)
}
QueryError::ExecutionError(IncorrectPrefetchResult { slow, prefetch }) => {
map.serialize_entry("incorrectPrefetch", &true)?;
map.serialize_entry("single", &SerializableValue(slow))?;
map.serialize_entry("prefetch", &SerializableValue(prefetch))?;
format!("{}", self)
}
_ => format!("{}", self),
};
map.serialize_entry("message", msg.as_str())?;
map.end()
}
}
impl CacheWeight for QueryError {
fn indirect_weight(&self) -> usize {
// Errors don't have a weight since they are never cached
0
}
}