-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathapi.rs
2365 lines (2145 loc) · 77.7 KB
/
api.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
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::{BTreeMap, HashMap};
use std::str::FromStr;
use std::sync::Arc;
use anyhow::Context;
use graphql_parser::Pos;
use lazy_static::lazy_static;
use thiserror::Error;
use crate::cheap_clone::CheapClone;
use crate::data::graphql::{ObjectOrInterface, ObjectTypeExt, TypeExt};
use crate::data::store::IdType;
use crate::env::ENV_VARS;
use crate::schema::{ast, META_FIELD_NAME, META_FIELD_TYPE, SCHEMA_TYPE_NAME};
use crate::data::graphql::ext::{
camel_cased_names, DefinitionExt, DirectiveExt, DocumentExt, ValueExt,
};
use crate::derive::CheapClone;
use crate::prelude::{q, r, s, DeploymentHash};
use super::{Aggregation, Field, InputSchema, Schema, TypeKind};
#[derive(Error, Debug)]
pub enum APISchemaError {
#[error("type {0} already exists in the input schema")]
TypeExists(String),
#[error("Type {0} not found")]
TypeNotFound(String),
#[error("Fulltext search is not yet deterministic")]
FulltextSearchNonDeterministic,
#[error("Illegal type for `id`: {0}")]
IllegalIdType(String),
#[error("Failed to create API schema: {0}")]
SchemaCreationFailed(String),
}
// The followoing types are defined in meta.graphql
const BLOCK_HEIGHT: &str = "Block_height";
const CHANGE_BLOCK_FILTER_NAME: &str = "BlockChangedFilter";
const ERROR_POLICY_TYPE: &str = "_SubgraphErrorPolicy_";
#[derive(Debug, PartialEq, Eq, Copy, Clone, CheapClone)]
pub enum ErrorPolicy {
Allow,
Deny,
}
impl std::str::FromStr for ErrorPolicy {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<ErrorPolicy, anyhow::Error> {
match s {
"allow" => Ok(ErrorPolicy::Allow),
"deny" => Ok(ErrorPolicy::Deny),
_ => Err(anyhow::anyhow!("failed to parse `{}` as ErrorPolicy", s)),
}
}
}
impl TryFrom<&q::Value> for ErrorPolicy {
type Error = anyhow::Error;
/// `value` should be the output of input value coercion.
fn try_from(value: &q::Value) -> Result<Self, Self::Error> {
match value {
q::Value::Enum(s) => ErrorPolicy::from_str(s),
_ => Err(anyhow::anyhow!("invalid `ErrorPolicy`")),
}
}
}
impl TryFrom<&r::Value> for ErrorPolicy {
type Error = anyhow::Error;
/// `value` should be the output of input value coercion.
fn try_from(value: &r::Value) -> Result<Self, Self::Error> {
match value {
r::Value::Enum(s) => ErrorPolicy::from_str(s),
_ => Err(anyhow::anyhow!("invalid `ErrorPolicy`")),
}
}
}
/// A GraphQL schema used for responding to queries. These schemas can be
/// generated in one of two ways:
///
/// (1) By calling `api_schema()` on an `InputSchema`. This is the way to
/// generate a query schema for a subgraph.
///
/// (2) By parsing an appropriate GraphQL schema from text and calling
/// `from_graphql_schema`. In that case, it's the caller's responsibility to
/// make sure that the schema has all the types needed for querying, in
/// particular `Query`
///
/// Because of the second point, once constructed, it can not be assumed
/// that an `ApiSchema` is based on an `InputSchema` and it can only be used
/// for querying.
#[derive(Debug)]
pub struct ApiSchema {
schema: Schema,
// Root types for the api schema.
pub query_type: Arc<s::ObjectType>,
object_types: HashMap<String, Arc<s::ObjectType>>,
}
impl ApiSchema {
/// Set up the `ApiSchema`, mostly by extracting important pieces of
/// information from it like `query_type` etc.
///
/// In addition, the API schema has an introspection schema mixed into
/// `api_schema`. In particular, the `Query` type has fields called
/// `__schema` and `__type`
pub(in crate::schema) fn from_api_schema(mut schema: Schema) -> Result<Self, anyhow::Error> {
add_introspection_schema(&mut schema.document);
let query_type = schema
.document
.get_root_query_type()
.context("no root `Query` in the schema")?
.clone();
let object_types = HashMap::from_iter(
schema
.document
.get_object_type_definitions()
.into_iter()
.map(|obj_type| (obj_type.name.clone(), Arc::new(obj_type.clone()))),
);
Ok(Self {
schema,
query_type: Arc::new(query_type),
object_types,
})
}
/// Create an API Schema that can be used to execute GraphQL queries.
/// This method is only meant for schemas that are not derived from a
/// subgraph schema, like the schema for the index-node server. Use
/// `InputSchema::api_schema` to get an API schema for a subgraph
pub fn from_graphql_schema(schema: Schema) -> Result<Self, anyhow::Error> {
Self::from_api_schema(schema)
}
pub fn document(&self) -> &s::Document {
&self.schema.document
}
pub fn id(&self) -> &DeploymentHash {
&self.schema.id
}
pub fn schema(&self) -> &Schema {
&self.schema
}
pub fn types_for_interface(&self) -> &BTreeMap<String, Vec<s::ObjectType>> {
&self.schema.types_for_interface
}
/// Returns `None` if the type implements no interfaces.
pub fn interfaces_for_type(&self, type_name: &str) -> Option<&Vec<s::InterfaceType>> {
self.schema.interfaces_for_type(type_name)
}
/// Return an `Arc` around the `ObjectType` from our internal cache
///
/// # Panics
/// If `obj_type` is not part of this schema, this function panics
pub fn object_type(&self, obj_type: &s::ObjectType) -> Arc<s::ObjectType> {
self.object_types
.get(&obj_type.name)
.expect("ApiSchema.object_type is only used with existing types")
.cheap_clone()
}
pub fn get_named_type(&self, name: &str) -> Option<&s::TypeDefinition> {
self.schema.document.get_named_type(name)
}
/// Returns true if the given type is an input type.
///
/// Uses the algorithm outlined on
/// https://facebook.github.io/graphql/draft/#IsInputType().
pub fn is_input_type(&self, t: &s::Type) -> bool {
match t {
s::Type::NamedType(name) => {
let named_type = self.get_named_type(name);
named_type.map_or(false, |type_def| match type_def {
s::TypeDefinition::Scalar(_)
| s::TypeDefinition::Enum(_)
| s::TypeDefinition::InputObject(_) => true,
_ => false,
})
}
s::Type::ListType(inner) => self.is_input_type(inner),
s::Type::NonNullType(inner) => self.is_input_type(inner),
}
}
pub fn get_root_query_type_def(&self) -> Option<&s::TypeDefinition> {
self.schema
.document
.definitions
.iter()
.find_map(|d| match d {
s::Definition::TypeDefinition(def @ s::TypeDefinition::Object(_)) => match def {
s::TypeDefinition::Object(t) if t.name == "Query" => Some(def),
_ => None,
},
_ => None,
})
}
pub fn object_or_interface(&self, name: &str) -> Option<ObjectOrInterface<'_>> {
if name.starts_with("__") {
INTROSPECTION_SCHEMA.object_or_interface(name)
} else {
self.schema.document.object_or_interface(name)
}
}
/// Returns the type definition that a field type corresponds to.
pub fn get_type_definition_from_field<'a>(
&'a self,
field: &s::Field,
) -> Option<&'a s::TypeDefinition> {
self.get_type_definition_from_type(&field.field_type)
}
/// Returns the type definition for a type.
pub fn get_type_definition_from_type<'a>(
&'a self,
t: &s::Type,
) -> Option<&'a s::TypeDefinition> {
match t {
s::Type::NamedType(name) => self.get_named_type(name),
s::Type::ListType(inner) => self.get_type_definition_from_type(inner),
s::Type::NonNullType(inner) => self.get_type_definition_from_type(inner),
}
}
#[cfg(debug_assertions)]
pub fn definitions(&self) -> impl Iterator<Item = &s::Definition> {
self.schema.document.definitions.iter()
}
}
lazy_static! {
static ref INTROSPECTION_SCHEMA: s::Document = {
let schema = include_str!("introspection.graphql");
s::parse_schema(schema).expect("the schema `introspection.graphql` is invalid")
};
pub static ref INTROSPECTION_QUERY_TYPE: ast::ObjectType = {
let root_query_type = INTROSPECTION_SCHEMA
.get_root_query_type()
.expect("Schema does not have a root query type");
ast::ObjectType::from(Arc::new(root_query_type.clone()))
};
}
pub fn is_introspection_field(name: &str) -> bool {
INTROSPECTION_QUERY_TYPE.field(name).is_some()
}
/// Extend `schema` with the definitions from the introspection schema and
/// modify the root query type to contain the fields from the introspection
/// schema's root query type.
///
/// This results in a schema that combines the original schema with the
/// introspection schema
fn add_introspection_schema(schema: &mut s::Document) {
fn introspection_fields() -> Vec<s::Field> {
// Generate fields for the root query fields in an introspection schema,
// the equivalent of the fields of the `Query` type:
//
// type Query {
// __schema: __Schema!
// __type(name: String!): __Type
// }
let type_args = vec![s::InputValue {
position: Pos::default(),
description: None,
name: "name".to_string(),
value_type: s::Type::NonNullType(Box::new(s::Type::NamedType("String".to_string()))),
default_value: None,
directives: vec![],
}];
vec![
s::Field {
position: Pos::default(),
description: None,
name: "__schema".to_string(),
arguments: vec![],
field_type: s::Type::NonNullType(Box::new(s::Type::NamedType(
"__Schema".to_string(),
))),
directives: vec![],
},
s::Field {
position: Pos::default(),
description: None,
name: "__type".to_string(),
arguments: type_args,
field_type: s::Type::NamedType("__Type".to_string()),
directives: vec![],
},
]
}
// Add all definitions from the introspection schema to the schema,
// except for the root query type as that qould clobber the 'real' root
// query type
schema.definitions.extend(
INTROSPECTION_SCHEMA
.definitions
.iter()
.filter(|dfn| !dfn.is_root_query_type())
.cloned(),
);
let query_type = schema
.definitions
.iter_mut()
.filter_map(|d| match d {
s::Definition::TypeDefinition(s::TypeDefinition::Object(t)) if t.name == "Query" => {
Some(t)
}
_ => None,
})
.peekable()
.next()
.expect("no root `Query` in the schema");
query_type.fields.append(&mut introspection_fields());
}
/// Derives a full-fledged GraphQL API schema from an input schema.
///
/// The input schema should only have type/enum/interface/union definitions
/// and must not include a root Query type. This Query type is derived, with
/// all its fields and their input arguments, based on the existing types.
pub(in crate::schema) fn api_schema(
input_schema: &InputSchema,
) -> Result<s::Document, APISchemaError> {
// Refactor: Don't clone the schema.
let mut api = init_api_schema(input_schema)?;
add_meta_field_type(&mut api.document);
add_types_for_object_types(&mut api, input_schema)?;
add_types_for_interface_types(&mut api, input_schema)?;
add_types_for_aggregation_types(&mut api, input_schema)?;
add_query_type(&mut api.document, input_schema)?;
Ok(api.document)
}
/// Initialize the API schema by copying type definitions from the input
/// schema. The copies of the type definitions are modified to allow
/// filtering and ordering of collections of entities.
fn init_api_schema(input_schema: &InputSchema) -> Result<Schema, APISchemaError> {
/// Add arguments to fields that reference collections of other entities to
/// allow e.g. filtering and ordering the collections. The `fields` should
/// be the fields of an object or interface type
fn add_collection_arguments(fields: &mut [s::Field], input_schema: &InputSchema) {
for field in fields.iter_mut().filter(|field| field.field_type.is_list()) {
let field_type = field.field_type.get_base_type();
// `field_type`` could be an enum or scalar, in which case
// `type_kind_str` will return `None``
if let Some(ops) = input_schema
.kind_of_declared_type(field_type)
.map(FilterOps::for_kind)
{
field.arguments = ops.collection_arguments(field_type);
}
}
}
fn add_type_def(
api: &mut s::Document,
type_def: &s::TypeDefinition,
input_schema: &InputSchema,
) -> Result<(), APISchemaError> {
match type_def {
s::TypeDefinition::Object(ot) => {
if ot.name != SCHEMA_TYPE_NAME {
let mut ot = ot.clone();
add_collection_arguments(&mut ot.fields, input_schema);
let typedef = s::TypeDefinition::Object(ot);
let def = s::Definition::TypeDefinition(typedef);
api.definitions.push(def);
}
}
s::TypeDefinition::Interface(it) => {
let mut it = it.clone();
add_collection_arguments(&mut it.fields, input_schema);
let typedef = s::TypeDefinition::Interface(it);
let def = s::Definition::TypeDefinition(typedef);
api.definitions.push(def);
}
s::TypeDefinition::Enum(et) => {
let typedef = s::TypeDefinition::Enum(et.clone());
let def = s::Definition::TypeDefinition(typedef);
api.definitions.push(def);
}
s::TypeDefinition::InputObject(_) => {
// We don't support input object types in subgraph schemas
// but some subgraphs use that to then pass parameters of
// that type to queries
api.definitions
.push(s::Definition::TypeDefinition(type_def.clone()));
}
s::TypeDefinition::Scalar(_) | s::TypeDefinition::Union(_) => {
// We don't support these type definitions in subgraph schemas
// but there are subgraphs out in the wild that contain them. We
// simply ignore them even though we should produce an error
}
}
Ok(())
}
let mut api = s::Document::default();
for defn in input_schema.schema().document.definitions.iter() {
match defn {
s::Definition::SchemaDefinition(_) | s::Definition::TypeExtension(_) => {
// We don't support these in subgraph schemas but there are
// subgraphs out in the wild that contain them. We simply
// ignore them even though we should produce an error
}
s::Definition::DirectiveDefinition(_) => {
// We don't really allow directive definitions in subgraph
// schemas, but the tests for introspection schemas create
// an input schema with a directive definition, and it's
// safer to allow it here rather than fail
api.definitions.push(defn.clone());
}
s::Definition::TypeDefinition(td) => add_type_def(&mut api, td, input_schema)?,
}
}
Schema::new(input_schema.id().clone(), api)
.map_err(|e| APISchemaError::SchemaCreationFailed(e.to_string()))
}
/// Adds a global `_Meta_` type to the schema. The `_meta` field
/// accepts values of this type
fn add_meta_field_type(api: &mut s::Document) {
lazy_static! {
static ref META_FIELD_SCHEMA: s::Document = {
let schema = include_str!("meta.graphql");
s::parse_schema(schema).expect("the schema `meta.graphql` is invalid")
};
}
api.definitions
.extend(META_FIELD_SCHEMA.definitions.iter().cloned());
}
fn add_types_for_object_types(
api: &mut Schema,
schema: &InputSchema,
) -> Result<(), APISchemaError> {
for (name, object_type) in schema.object_types() {
add_order_by_type(&mut api.document, name, &object_type.fields)?;
add_filter_type(api, name, &object_type.fields)?;
}
Ok(())
}
/// Adds `*_orderBy` and `*_filter` enum types for the given interfaces to the schema.
fn add_types_for_interface_types(
api: &mut Schema,
input_schema: &InputSchema,
) -> Result<(), APISchemaError> {
for (name, interface_type) in input_schema.interface_types() {
add_order_by_type(&mut api.document, name, &interface_type.fields)?;
add_filter_type(api, name, &interface_type.fields)?;
}
Ok(())
}
fn add_types_for_aggregation_types(
api: &mut Schema,
input_schema: &InputSchema,
) -> Result<(), APISchemaError> {
for (name, agg_type) in input_schema.aggregation_types() {
// Combine regular fields and aggregate fields for ordering
let mut all_fields = agg_type.fields.to_vec();
for agg in agg_type.aggregates.iter() {
all_fields.push(agg.as_agg_field());
}
add_order_by_type(&mut api.document, name, &all_fields)?;
add_aggregation_filter_type(api, name, agg_type)?;
}
Ok(())
}
/// Adds a `<type_name>_orderBy` enum type for the given fields to the schema.
fn add_order_by_type(
api: &mut s::Document,
type_name: &str,
fields: &[Field],
) -> Result<(), APISchemaError> {
let type_name = format!("{}_orderBy", type_name);
match api.get_named_type(&type_name) {
None => {
let typedef = s::TypeDefinition::Enum(s::EnumType {
position: Pos::default(),
description: None,
name: type_name,
directives: vec![],
values: field_enum_values(api, fields)?,
});
let def = s::Definition::TypeDefinition(typedef);
api.definitions.push(def);
}
Some(_) => return Err(APISchemaError::TypeExists(type_name)),
}
Ok(())
}
/// Generates enum values for the given set of fields.
fn field_enum_values(
schema: &s::Document,
fields: &[Field],
) -> Result<Vec<s::EnumValue>, APISchemaError> {
let mut enum_values = vec![];
for field in fields {
enum_values.push(s::EnumValue {
position: Pos::default(),
description: None,
name: field.name.to_string(),
directives: vec![],
});
enum_values.extend(field_enum_values_from_child_entity(schema, field)?);
}
Ok(enum_values)
}
fn enum_value_from_child_entity_field(
schema: &s::Document,
parent_field_name: &str,
field: &s::Field,
) -> Option<s::EnumValue> {
if ast::is_list_or_non_null_list_field(field) || ast::is_entity_type(schema, &field.field_type)
{
// Sorting on lists or entities is not supported.
None
} else {
Some(s::EnumValue {
position: Pos::default(),
description: None,
name: format!("{}__{}", parent_field_name, field.name),
directives: vec![],
})
}
}
fn field_enum_values_from_child_entity(
schema: &s::Document,
field: &Field,
) -> Result<Vec<s::EnumValue>, APISchemaError> {
fn resolve_supported_type_name(field_type: &s::Type) -> Option<&String> {
match field_type {
s::Type::NamedType(name) => Some(name),
s::Type::ListType(_) => None,
s::Type::NonNullType(of_type) => resolve_supported_type_name(of_type),
}
}
let type_name = match ENV_VARS.graphql.disable_child_sorting {
true => None,
false => resolve_supported_type_name(&field.field_type),
};
Ok(match type_name {
Some(name) => {
let named_type = schema
.get_named_type(name)
.ok_or_else(|| APISchemaError::TypeNotFound(name.clone()))?;
match named_type {
s::TypeDefinition::Object(s::ObjectType { fields, .. })
| s::TypeDefinition::Interface(s::InterfaceType { fields, .. }) => fields
.iter()
.filter_map(|f| {
enum_value_from_child_entity_field(schema, field.name.as_str(), f)
})
.collect(),
_ => vec![],
}
}
None => vec![],
})
}
/// Create an input object type definition for the `where` argument of a
/// collection. The `name` is the name of the filter type, e.g.,
/// `User_filter` and the fields are all the possible filters. This function
/// adds fields for boolean `and` and `or` filters and for filtering by
/// block change to the given fields.
fn filter_type_defn(name: String, mut fields: Vec<s::InputValue>) -> s::Definition {
fields.push(block_changed_filter_argument());
if !ENV_VARS.graphql.disable_bool_filters {
fields.push(s::InputValue {
position: Pos::default(),
description: None,
name: "and".to_string(),
value_type: s::Type::ListType(Box::new(s::Type::NamedType(name.clone()))),
default_value: None,
directives: vec![],
});
fields.push(s::InputValue {
position: Pos::default(),
description: None,
name: "or".to_string(),
value_type: s::Type::ListType(Box::new(s::Type::NamedType(name.clone()))),
default_value: None,
directives: vec![],
});
}
let typedef = s::TypeDefinition::InputObject(s::InputObjectType {
position: Pos::default(),
description: None,
name,
directives: vec![],
fields,
});
s::Definition::TypeDefinition(typedef)
}
/// Selector for the kind of field filters to generate
#[derive(Copy, Clone)]
enum FilterOps {
/// Use ops for object and interface types
Object,
/// Use ops for aggregation types
Aggregation,
}
impl FilterOps {
fn for_type<'a>(&self, scalar_type: &'a s::ScalarType) -> FilterOpsSet<'a> {
match self {
Self::Object => FilterOpsSet::Object(&scalar_type.name),
Self::Aggregation => FilterOpsSet::Aggregation(&scalar_type.name),
}
}
fn for_kind(kind: TypeKind) -> FilterOps {
match kind {
TypeKind::Object | TypeKind::Interface => FilterOps::Object,
TypeKind::Aggregation => FilterOps::Aggregation,
}
}
/// Generates arguments for collection queries of a named type (e.g. User).
fn collection_arguments(&self, type_name: &str) -> Vec<s::InputValue> {
// `first` and `skip` should be non-nullable, but the Apollo graphql client
// exhibts non-conforming behaviour by erroing if no value is provided for a
// non-nullable field, regardless of the presence of a default.
let mut skip = input_value("skip", "", s::Type::NamedType("Int".to_string()));
skip.default_value = Some(s::Value::Int(0.into()));
let mut first = input_value("first", "", s::Type::NamedType("Int".to_string()));
first.default_value = Some(s::Value::Int(100.into()));
let filter_type = s::Type::NamedType(format!("{}_filter", type_name));
let filter = input_value("where", "", filter_type);
let order_by = match self {
FilterOps::Object => vec![
input_value(
"orderBy",
"",
s::Type::NamedType(format!("{}_orderBy", type_name)),
),
input_value(
"orderDirection",
"",
s::Type::NamedType("OrderDirection".to_string()),
),
],
FilterOps::Aggregation => vec![
input_value(
"interval",
"",
s::Type::NonNullType(Box::new(s::Type::NamedType(
"Aggregation_interval".to_string(),
))),
),
input_value(
"orderBy",
"",
s::Type::NamedType(format!("{}_orderBy", type_name)),
),
input_value(
"orderDirection",
"",
s::Type::NamedType("OrderDirection".to_string()),
),
],
};
let mut args = vec![skip, first];
args.extend(order_by);
args.push(filter);
args
}
}
#[derive(Copy, Clone)]
enum FilterOpsSet<'a> {
Object(&'a str),
Aggregation(&'a str),
}
impl<'a> FilterOpsSet<'a> {
fn type_name(&self) -> &'a str {
match self {
Self::Object(type_name) | Self::Aggregation(type_name) => type_name,
}
}
}
/// Adds a `<type_name>_filter` enum type for the given fields to the
/// schema. Used for object and interface types
fn add_filter_type(
api: &mut Schema,
type_name: &str,
fields: &[Field],
) -> Result<(), APISchemaError> {
let filter_type_name = format!("{}_filter", type_name);
if api.document.get_named_type(&filter_type_name).is_some() {
return Err(APISchemaError::TypeExists(filter_type_name));
}
let filter_fields = field_input_values(api, fields, FilterOps::Object)?;
let defn = filter_type_defn(filter_type_name, filter_fields);
api.document.definitions.push(defn);
Ok(())
}
fn add_aggregation_filter_type(
api: &mut Schema,
type_name: &str,
agg: &Aggregation,
) -> Result<(), APISchemaError> {
let filter_type_name = format!("{}_filter", type_name);
if api.document.get_named_type(&filter_type_name).is_some() {
return Err(APISchemaError::TypeExists(filter_type_name));
}
let filter_fields = field_input_values(api, &agg.fields, FilterOps::Aggregation)?;
let defn = filter_type_defn(filter_type_name, filter_fields);
api.document.definitions.push(defn);
Ok(())
}
/// Generates `*_filter` input values for the given set of fields.
fn field_input_values(
schema: &Schema,
fields: &[Field],
ops: FilterOps,
) -> Result<Vec<s::InputValue>, APISchemaError> {
let mut input_values = vec![];
for field in fields {
input_values.extend(field_filter_input_values(schema, field, ops)?);
}
Ok(input_values)
}
/// Generates `*_filter` input values for the given field.
fn field_filter_input_values(
schema: &Schema,
field: &Field,
ops: FilterOps,
) -> Result<Vec<s::InputValue>, APISchemaError> {
let type_name = field.field_type.get_base_type();
if field.is_list() {
Ok(field_list_filter_input_values(schema, field)?.unwrap_or_default())
} else {
let named_type = schema
.document
.get_named_type(type_name)
.ok_or_else(|| APISchemaError::TypeNotFound(type_name.to_string()))?;
Ok(match named_type {
s::TypeDefinition::Object(_) | s::TypeDefinition::Interface(_) => {
let scalar_type = id_type_as_scalar(schema, named_type)?.unwrap();
let mut input_values = if field.is_derived() {
// Only add `where` filter fields for object and interface fields
// if they are not @derivedFrom
vec![]
} else {
// We allow filtering with `where: { other: "some-id" }` and
// `where: { others: ["some-id", "other-id"] }`. In both cases,
// we allow ID strings as the values to be passed to these
// filters.
field_scalar_filter_input_values(
&schema.document,
field,
ops.for_type(&scalar_type),
)
};
extend_with_child_filter_input_value(field, type_name, &mut input_values);
input_values
}
s::TypeDefinition::Scalar(ref t) => {
field_scalar_filter_input_values(&schema.document, field, ops.for_type(t))
}
s::TypeDefinition::Enum(ref t) => {
field_enum_filter_input_values(&schema.document, field, t)
}
_ => vec![],
})
}
}
fn id_type_as_scalar(
schema: &Schema,
typedef: &s::TypeDefinition,
) -> Result<Option<s::ScalarType>, APISchemaError> {
let id_type = match typedef {
s::TypeDefinition::Object(obj_type) => IdType::try_from(obj_type)
.map(Option::Some)
.map_err(|_| APISchemaError::IllegalIdType(obj_type.name.to_owned())),
s::TypeDefinition::Interface(intf_type) => {
match schema
.types_for_interface
.get(&intf_type.name)
.and_then(|obj_types| obj_types.first())
{
None => Ok(Some(IdType::String)),
Some(obj_type) => IdType::try_from(obj_type)
.map(Option::Some)
.map_err(|_| APISchemaError::IllegalIdType(obj_type.name.to_owned())),
}
}
_ => Ok(None),
}?;
let scalar_type = id_type.map(|id_type| match id_type {
IdType::String | IdType::Bytes => s::ScalarType::new(String::from("String")),
// It would be more logical to use "Int8" here, but currently, that
// leads to values being turned into strings, not i64 which causes
// database queries to fail in various places. Once this is fixed
// (check e.g., `Value::coerce_scalar` in `graph/src/data/value.rs`)
// we can turn that into "Int8". For now, queries can only query
// Int8 id values up to i32::MAX.
IdType::Int8 => s::ScalarType::new(String::from("Int")),
});
Ok(scalar_type)
}
fn field_filter_ops(set: FilterOpsSet<'_>) -> &'static [&'static str] {
use FilterOpsSet::*;
match set {
Object("Boolean") => &["", "not", "in", "not_in"],
Object("Bytes") => &[
"",
"not",
"gt",
"lt",
"gte",
"lte",
"in",
"not_in",
"contains",
"not_contains",
],
Object("ID") => &["", "not", "gt", "lt", "gte", "lte", "in", "not_in"],
Object("BigInt") | Object("BigDecimal") | Object("Int") | Object("Int8")
| Object("Timestamp") => &["", "not", "gt", "lt", "gte", "lte", "in", "not_in"],
Object("String") => &[
"",
"not",
"gt",
"lt",
"gte",
"lte",
"in",
"not_in",
"contains",
"contains_nocase",
"not_contains",
"not_contains_nocase",
"starts_with",
"starts_with_nocase",
"not_starts_with",
"not_starts_with_nocase",
"ends_with",
"ends_with_nocase",
"not_ends_with",
"not_ends_with_nocase",
],
Aggregation("BigInt")
| Aggregation("BigDecimal")
| Aggregation("Int")
| Aggregation("Int8")
| Aggregation("Timestamp") => &["", "gt", "lt", "gte", "lte", "in"],
Object(_) => &["", "not"],
Aggregation(_) => &[""],
}
}
/// Generates `*_filter` input values for the given scalar field.
fn field_scalar_filter_input_values(
_schema: &s::Document,
field: &Field,
set: FilterOpsSet<'_>,
) -> Vec<s::InputValue> {
field_filter_ops(set)
.into_iter()
.map(|filter_type| {
let field_type = s::Type::NamedType(set.type_name().to_string());
let value_type = match *filter_type {
"in" | "not_in" => {
s::Type::ListType(Box::new(s::Type::NonNullType(Box::new(field_type))))
}
_ => field_type,
};
input_value(&field.name, filter_type, value_type)
})
.collect()
}
/// Appends a child filter to input values
fn extend_with_child_filter_input_value(
field: &Field,
field_type_name: &str,
input_values: &mut Vec<s::InputValue>,
) {
input_values.push(input_value(
&format!("{}_", field.name),
"",
s::Type::NamedType(format!("{}_filter", field_type_name)),
));
}
/// Generates `*_filter` input values for the given enum field.
fn field_enum_filter_input_values(
_schema: &s::Document,
field: &Field,
field_type: &s::EnumType,
) -> Vec<s::InputValue> {
vec!["", "not", "in", "not_in"]
.into_iter()
.map(|filter_type| {
let field_type = s::Type::NamedType(field_type.name.clone());
let value_type = match filter_type {
"in" | "not_in" => {
s::Type::ListType(Box::new(s::Type::NonNullType(Box::new(field_type))))
}
_ => field_type,
};
input_value(&field.name, filter_type, value_type)
})
.collect()
}
/// Generates `*_filter` input values for the given list field.
fn field_list_filter_input_values(
schema: &Schema,
field: &Field,
) -> Result<Option<Vec<s::InputValue>>, APISchemaError> {
// Only add a filter field if the type of the field exists in the schema
let typedef = match ast::get_type_definition_from_type(&schema.document, &field.field_type) {
Some(typedef) => typedef,
None => return Ok(None),
};
// Decide what type of values can be passed to the filter. In the case
// one-to-many or many-to-many object or interface fields that are not
// derived, we allow ID strings to be passed on.
// Adds child filter only to object types.
let (input_field_type, parent_type_name) = match typedef {
s::TypeDefinition::Object(s::ObjectType { name, .. })
| s::TypeDefinition::Interface(s::InterfaceType { name, .. }) => {
if field.is_derived() {
(None, Some(name.clone()))
} else {
let scalar_type = id_type_as_scalar(schema, typedef)?.unwrap();
let named_type = s::Type::NamedType(scalar_type.name);
(Some(named_type), Some(name.clone()))
}
}
s::TypeDefinition::Scalar(ref t) => (Some(s::Type::NamedType(t.name.clone())), None),
s::TypeDefinition::Enum(ref t) => (Some(s::Type::NamedType(t.name.clone())), None),
s::TypeDefinition::InputObject(_) | s::TypeDefinition::Union(_) => (None, None),
};
let mut input_values: Vec<s::InputValue> = match input_field_type {
None => {
vec![]