-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathinput_schema.rs
More file actions
1776 lines (1605 loc) · 63.3 KB
/
input_schema.rs
File metadata and controls
1776 lines (1605 loc) · 63.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
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, BTreeSet};
use std::sync::Arc;
use anyhow::{anyhow, Error};
use store::Entity;
use crate::bail;
use crate::cheap_clone::CheapClone;
use crate::components::store::LoadRelatedRequest;
use crate::data::graphql::ext::DirectiveFinder;
use crate::data::graphql::{DirectiveExt, DocumentExt, ObjectTypeExt, TypeExt, ValueExt};
use crate::data::store::{
self, EntityValidationError, IdType, IntoEntityIterator, TryIntoEntityIterator, ValueType, ID,
};
use crate::data::value::Word;
use crate::prelude::q::Value;
use crate::prelude::{s, DeploymentHash};
use crate::schema::api::api_schema;
use crate::util::intern::{Atom, AtomPool};
use super::fulltext::FulltextDefinition;
use super::{
ApiSchema, AsEntityTypeName, EntityType, Schema, SchemaValidationError, SCHEMA_TYPE_NAME,
};
/// The name of the PoI entity type
pub(crate) const POI_OBJECT: &str = "Poi$";
/// The name of the digest attribute of POI entities
const POI_DIGEST: &str = "digest";
/// The internal representation of a subgraph schema, i.e., the
/// `schema.graphql` file that is part of a subgraph. Any code that deals
/// with writing a subgraph should use this struct. Code that deals with
/// querying subgraphs will instead want to use an `ApiSchema` which can be
/// generated with the `api_schema` method on `InputSchema`
///
/// There's no need to put this into an `Arc`, since `InputSchema` already
/// does that internally and is `CheapClone`
#[derive(Clone, Debug, PartialEq)]
pub struct InputSchema {
inner: Arc<Inner>,
}
#[derive(Debug, PartialEq)]
enum TypeKind {
MutableObject(ObjectType),
ImmutableObject(ObjectType),
Interface(InterfaceType),
}
impl TypeKind {
fn is_object(&self) -> bool {
match self {
TypeKind::MutableObject(_) | TypeKind::ImmutableObject(_) => true,
TypeKind::Interface(_) => false,
}
}
fn is_interface(&self) -> bool {
match self {
TypeKind::MutableObject(_) | TypeKind::ImmutableObject(_) => false,
TypeKind::Interface(_) => true,
}
}
fn id_type(&self) -> Option<IdType> {
match self {
TypeKind::MutableObject(obj_type) | TypeKind::ImmutableObject(obj_type) => {
Some(obj_type.id_type)
}
TypeKind::Interface(intf_type) => Some(intf_type.id_type),
}
}
fn fields(&self) -> impl Iterator<Item = &Field> {
match self {
TypeKind::MutableObject(obj_type) | TypeKind::ImmutableObject(obj_type) => {
obj_type.fields.iter()
}
TypeKind::Interface(intf_type) => intf_type.fields.iter(),
}
}
fn name(&self) -> Atom {
match self {
TypeKind::MutableObject(obj_type) | TypeKind::ImmutableObject(obj_type) => {
obj_type.name
}
TypeKind::Interface(intf_type) => intf_type.name,
}
}
}
#[derive(Debug, PartialEq)]
struct TypeInfo {
kind: TypeKind,
fields: Box<[Atom]>,
}
impl TypeInfo {
fn new(pool: &AtomPool, kind: TypeKind) -> Self {
// The `unwrap` of `lookup` is safe because the pool was just
// constructed against the underlying schema
let fields = kind
.fields()
.map(|field| pool.lookup(&field.name).unwrap())
.collect::<Vec<_>>()
.into_boxed_slice();
Self { kind, fields }
}
fn name(&self) -> Atom {
self.kind.name()
}
fn for_object(schema: &Schema, pool: &AtomPool, obj_type: &s::ObjectType) -> Self {
let shared_interfaces: Vec<_> = match schema.interfaces_for_type(&obj_type.name) {
Some(intfs) => {
let mut shared_interfaces: Vec<_> = intfs
.iter()
.flat_map(|intf| &schema.types_for_interface[&intf.name])
.filter(|other| other.name != obj_type.name)
.map(|obj_type| pool.lookup(&obj_type.name).unwrap())
.collect();
shared_interfaces.sort();
shared_interfaces.dedup();
shared_interfaces
}
None => Vec::new(),
};
let object_type =
ObjectType::new(schema, pool, obj_type, shared_interfaces.into_boxed_slice());
let kind = if obj_type.is_immutable() {
TypeKind::ImmutableObject(object_type)
} else {
TypeKind::MutableObject(object_type)
};
Self::new(pool, kind)
}
fn for_interface(schema: &Schema, pool: &AtomPool, intf_type: &s::InterfaceType) -> Self {
static EMPTY_VEC: [s::ObjectType; 0] = [];
let implementers = schema
.types_for_interface
.get(&intf_type.name)
.map(|impls| impls.as_slice())
.unwrap_or_else(|| EMPTY_VEC.as_slice());
let intf_type = InterfaceType::new(schema, pool, intf_type, implementers);
Self::new(pool, TypeKind::Interface(intf_type))
}
fn for_poi(pool: &AtomPool) -> Self {
// The way we handle the PoI type is a bit of a hack. We pretend
// it's an object type, but trying to look up the `s::ObjectType`
// for it will turn up nothing.
// See also https://github.com/graphprotocol/graph-node/issues/4873
let fields =
vec![pool.lookup(&ID).unwrap(), pool.lookup(POI_DIGEST).unwrap()].into_boxed_slice();
Self {
kind: TypeKind::MutableObject(ObjectType::for_poi(pool)),
fields,
}
}
fn interfaces(&self) -> impl Iterator<Item = &str> {
const NO_INTF: [Word; 0] = [];
let interfaces = match &self.kind {
TypeKind::MutableObject(obj_type) | TypeKind::ImmutableObject(obj_type) => {
&obj_type.interfaces
}
TypeKind::Interface(_) => NO_INTF.as_slice(),
};
interfaces.iter().map(|interface| interface.as_str())
}
fn object_type(&self) -> Option<&ObjectType> {
match &self.kind {
TypeKind::MutableObject(obj_type) | TypeKind::ImmutableObject(obj_type) => {
Some(obj_type)
}
TypeKind::Interface(_) => None,
}
}
}
#[derive(PartialEq, Debug)]
pub struct Field {
pub name: Word,
pub field_type: s::Type,
pub value_type: ValueType,
pub is_derived: bool,
}
impl Field {
pub fn new(schema: &Schema, name: &str, field_type: &s::Type, is_derived: bool) -> Self {
let value_type = Self::scalar_value_type(&schema, field_type);
Self {
name: Word::from(name),
field_type: field_type.clone(),
value_type,
is_derived,
}
}
fn scalar_value_type(schema: &Schema, field_type: &s::Type) -> ValueType {
use s::TypeDefinition as t;
match field_type {
s::Type::NamedType(name) => name.parse::<ValueType>().unwrap_or_else(|_| {
match schema.document.get_named_type(name) {
Some(t::Object(obj_type)) => {
let id = obj_type.field(&*ID).expect("all object types have an id");
Self::scalar_value_type(schema, &id.field_type)
}
Some(t::Interface(intf)) => {
// Validation checks that all implementors of an
// interface use the same type for `id`. It is
// therefore enough to use the id type of one of
// the implementors
match schema
.types_for_interface
.get(&intf.name)
.expect("interface type names are known")
.first()
{
None => {
// Nothing is implementing this interface; we assume it's of type string
// see also: id-type-for-unimplemented-interfaces
ValueType::String
}
Some(obj_type) => {
let id = obj_type.field(&*ID).expect("all object types have an id");
Self::scalar_value_type(schema, &id.field_type)
}
}
}
Some(t::Enum(_)) => ValueType::String,
Some(t::Scalar(_)) => unreachable!("user-defined scalars are not used"),
Some(t::Union(_)) => unreachable!("unions are not used"),
Some(t::InputObject(_)) => unreachable!("inputObjects are not used"),
None => unreachable!("names of field types have been validated"),
}
}),
s::Type::NonNullType(inner) => Self::scalar_value_type(schema, inner),
s::Type::ListType(inner) => Self::scalar_value_type(schema, inner),
}
}
}
#[derive(PartialEq, Debug)]
pub struct ObjectType {
pub name: Atom,
pub id_type: IdType,
pub fields: Box<[Field]>,
interfaces: Box<[Word]>,
shared_interfaces: Box<[Atom]>,
}
impl ObjectType {
fn new(
schema: &Schema,
pool: &AtomPool,
object_type: &s::ObjectType,
shared_interfaces: Box<[Atom]>,
) -> Self {
let id_type = IdType::try_from(object_type).expect("validation caught any issues here");
let fields = object_type
.fields
.iter()
.map(|field| {
let is_derived = field.is_derived();
Field::new(schema, &field.name, &field.field_type, is_derived)
})
.collect();
let interfaces = object_type
.implements_interfaces
.iter()
.map(|intf| Word::from(intf.to_owned()))
.collect();
let name = pool
.lookup(&object_type.name)
.expect("object type names have been interned");
Self {
name,
fields,
id_type,
interfaces,
shared_interfaces,
}
}
fn for_poi(pool: &AtomPool) -> Self {
let fields = vec![
Field {
name: ID.clone(),
field_type: s::Type::NamedType("ID".to_string()),
value_type: ValueType::String,
is_derived: false,
},
Field {
name: Word::from(POI_DIGEST),
field_type: s::Type::NamedType("String".to_string()),
value_type: ValueType::String,
is_derived: false,
},
]
.into_boxed_slice();
let name = pool
.lookup(POI_OBJECT)
.expect("POI_OBJECT has been interned");
Self {
name,
interfaces: Box::new([]),
id_type: IdType::String,
fields,
shared_interfaces: Box::new([]),
}
}
fn field(&self, name: &str) -> Option<&Field> {
self.fields.iter().find(|field| field.name == name)
}
}
#[derive(PartialEq, Debug)]
pub struct InterfaceType {
pub name: Atom,
/// For interfaces, the type of the `id` field is the type of the `id`
/// field of the object types that implement it; validations ensure that
/// it is the same for all implementers of an interface. If an interface
/// is not implemented at all, we arbitrarily use `String`
pub id_type: IdType,
pub fields: Vec<Field>,
}
impl InterfaceType {
fn new(
schema: &Schema,
pool: &AtomPool,
interface_type: &s::InterfaceType,
implementers: &[s::ObjectType],
) -> Self {
let fields = interface_type
.fields
.iter()
.map(|field| Field::new(schema, &field.name, &field.field_type, false))
.collect();
let name = pool
.lookup(&interface_type.name)
.expect("interface type names have been interned");
let id_type = implementers
.first()
.map(|obj_type| IdType::try_from(obj_type).expect("validation caught any issues here"))
.unwrap_or(IdType::String);
Self {
name,
id_type,
fields,
}
}
}
#[derive(Debug, PartialEq)]
struct EnumMap(BTreeMap<String, Arc<BTreeSet<String>>>);
impl EnumMap {
fn new(schema: &Schema) -> Self {
let map = schema
.document
.get_enum_definitions()
.iter()
.map(|enum_type| {
(
enum_type.name.clone(),
Arc::new(
enum_type
.values
.iter()
.map(|value| value.name.clone())
.collect::<BTreeSet<_>>(),
),
)
})
.collect();
EnumMap(map)
}
fn names(&self) -> impl Iterator<Item = &str> {
self.0.keys().map(|name| name.as_str())
}
fn contains_key(&self, name: &str) -> bool {
self.0.contains_key(name)
}
fn values(&self, name: &str) -> Option<Arc<BTreeSet<String>>> {
self.0.get(name).cloned()
}
}
#[derive(Debug, PartialEq)]
pub struct Inner {
schema: Schema,
/// A list of all the object and interface types in the `schema` with
/// some important information extracted from the schema. The list is
/// sorted by the name atom (not the string name) of the types
type_infos: Box<[TypeInfo]>,
enum_map: EnumMap,
pool: Arc<AtomPool>,
}
impl CheapClone for InputSchema {
fn cheap_clone(&self) -> Self {
InputSchema {
inner: self.inner.cheap_clone(),
}
}
}
impl InputSchema {
/// A convenience function for creating an `InputSchema` from the string
/// representation of the subgraph's GraphQL schema `raw` and its
/// deployment hash `id`. The returned schema is fully validated.
pub fn parse(raw: &str, id: DeploymentHash) -> Result<Self, Error> {
let schema = Schema::parse(raw, id.clone())?;
validations::validate(&schema).map_err(|errors| {
anyhow!(
"Validation errors in subgraph `{}`:\n{}",
id,
errors
.into_iter()
.enumerate()
.map(|(n, e)| format!(" ({}) - {}", n + 1, e))
.collect::<Vec<_>>()
.join("\n")
)
})?;
let pool = Arc::new(atom_pool(&schema.document));
let obj_types = schema
.document
.get_object_type_definitions()
.into_iter()
.filter(|obj_type| obj_type.name != SCHEMA_TYPE_NAME)
.map(|obj_type| TypeInfo::for_object(&schema, &pool, obj_type));
let intf_types = schema
.document
.get_interface_type_definitions()
.into_iter()
.map(|intf_type| TypeInfo::for_interface(&schema, &pool, intf_type));
let mut type_infos: Vec<_> = obj_types
.chain(intf_types)
.chain(vec![TypeInfo::for_poi(&pool)])
.collect();
type_infos.sort_by_key(|ti| ti.name());
let type_infos = type_infos.into_boxed_slice();
let enum_map = EnumMap::new(&schema);
Ok(Self {
inner: Arc::new(Inner {
schema,
type_infos,
enum_map,
pool,
}),
})
}
pub fn validate(raw: &str, id: DeploymentHash) -> Vec<SchemaValidationError> {
let schema = match Schema::parse(raw, id.clone()) {
Ok(schema) => schema,
Err(err) => return vec![SchemaValidationError::InvalidSchema(err.to_string())],
};
match validations::validate(&schema) {
Ok(_) => vec![],
Err(errors) => errors,
}
}
/// Convenience for tests to construct an `InputSchema`
///
/// # Panics
///
/// If the `document` or `hash` can not be successfully converted
#[cfg(debug_assertions)]
#[track_caller]
pub fn raw(document: &str, hash: &str) -> Self {
let hash = DeploymentHash::new(hash).unwrap();
Self::parse(document, hash).unwrap()
}
pub fn schema(&self) -> &Schema {
&self.inner.schema
}
/// Generate the `ApiSchema` for use with GraphQL queries for this
/// `InputSchema`
pub fn api_schema(&self) -> Result<ApiSchema, anyhow::Error> {
let mut schema = self.inner.schema.clone();
schema.document = api_schema(&self.inner.schema)?;
schema.add_subgraph_id_directives(schema.id.clone());
ApiSchema::from_api_schema(schema)
}
/// Returns the field that has the relationship with the key requested
/// This works as a reverse search for the Field related to the query
///
/// example:
///
/// type Account @entity {
/// wallets: [Wallet!]! @derivedFrom(field: "account")
/// }
/// type Wallet {
/// account: Account!
/// balance: Int!
/// }
///
/// When asked to load the related entities from "Account" in the field "wallets"
/// This function will return the type "Wallet" with the field "account"
pub fn get_field_related(
&self,
key: &LoadRelatedRequest,
) -> Result<(EntityType, &Field), Error> {
fn field_err(key: &LoadRelatedRequest, err: &str) -> Error {
anyhow!(
"Entity {}[{}]: {err} `{}`",
key.entity_type,
key.entity_id,
key.entity_field,
)
}
let field = self
.inner
.schema
.document
.get_object_type_definition(key.entity_type.as_str())
.ok_or_else(|| field_err(key, "unknown entity type"))?
.field(&key.entity_field)
.ok_or_else(|| field_err(key, "unknown field"))?;
if !field.is_derived() {
return Err(field_err(key, "field is not derived"));
}
let derived_from = field.find_directive("derivedFrom").unwrap();
let entity_type = self.entity_type(field.field_type.get_base_type())?;
let field_name = derived_from.argument("field").unwrap();
let field = self
.find_object_type(entity_type.atom)
.ok_or_else(|| field_err(key, "unknown entity type"))?
.field(field_name.as_str().unwrap())
.ok_or_else(|| field_err(key, "unknown field"))?;
Ok((entity_type, field))
}
fn type_info(&self, atom: Atom) -> Result<&TypeInfo, Error> {
self.inner
.type_infos
.binary_search_by_key(&atom, |ti| ti.name())
.map(|idx| &self.inner.type_infos[idx])
.map_err(|_| match self.inner.pool.get(atom) {
Some(name) => anyhow!(
"internal error: entity type `{}` does not exist in {}",
name,
self.inner.schema.id
),
None => anyhow!(
"Invalid atom {atom:?} for type_info lookup in {} (atom is probably from a different pool)", self.inner.schema.id
),
})
}
pub(in crate::schema) fn id_type(&self, entity_type: Atom) -> Result<store::IdType, Error> {
let type_info = self.type_info(entity_type)?;
type_info.kind.id_type().ok_or_else(|| {
let name = self.inner.pool.get(entity_type).unwrap();
anyhow!("Entity type `{}` does not have an `id` field", name)
})
}
/// Check if `entity_type` is an immutable object type
pub(in crate::schema) fn is_immutable(&self, entity_type: Atom) -> bool {
self.type_info(entity_type)
.map(|ti| matches!(ti.kind, TypeKind::ImmutableObject(_)))
.unwrap_or(false)
}
/// Return true if `type_name` is the name of an object or interface type
pub fn is_reference(&self, type_name: &str) -> bool {
self.inner
.pool
.lookup(type_name)
.and_then(|atom| {
self.type_info(atom)
.ok()
.map(|ti| ti.kind.is_object() || ti.kind.is_interface())
})
.unwrap_or(false)
}
/// Return a list of the interfaces that `entity_type` implements
pub fn interfaces(&self, entity_type: Atom) -> impl Iterator<Item = &InterfaceType> {
let obj_type = self.type_info(entity_type).unwrap();
obj_type.interfaces().map(|intf| {
let atom = self.inner.pool.lookup(intf).unwrap();
match self.type_info(atom).unwrap().kind {
TypeKind::Interface(ref intf_type) => intf_type,
_ => unreachable!("expected `{intf}` to refer to an interface"),
}
})
}
/// Return a list of all entity types that implement one of the
/// interfaces that `entity_type` implements
pub(in crate::schema) fn share_interfaces(
&self,
entity_type: Atom,
) -> Result<Vec<EntityType>, Error> {
let obj_type = match &self.type_info(entity_type)?.kind {
TypeKind::MutableObject(obj_type) | TypeKind::ImmutableObject(obj_type) => obj_type,
_ => bail!(
"expected `{}` to refer to an object type",
self.inner.pool.get(entity_type).unwrap_or("<unknown>")
),
};
Ok(obj_type
.shared_interfaces
.into_iter()
.map(|atom| EntityType::new(self.cheap_clone(), *atom))
.collect())
}
pub(in crate::schema) fn find_object_type(&self, entity_type: Atom) -> Option<&ObjectType> {
self.type_info(entity_type).ok().map(|ti| match &ti.kind {
TypeKind::MutableObject(obj_type) | TypeKind::ImmutableObject(obj_type) => obj_type,
TypeKind::Interface(_) => {
let name = self.inner.pool.get(entity_type).unwrap();
unreachable!("expected `{}` to refer to an object type", name)
}
})
}
/// Return a list of the names of all enum types
pub fn enum_types(&self) -> impl Iterator<Item = &str> {
self.inner.enum_map.names()
}
/// Check if `name` is the name of an enum type
pub fn is_enum_type(&self, name: &str) -> bool {
self.inner.enum_map.contains_key(name)
}
/// Return a list of the values of the enum type `name`
pub fn enum_values(&self, name: &str) -> Option<Arc<BTreeSet<String>>> {
self.inner.enum_map.values(name)
}
pub fn entity_types(&self) -> Vec<EntityType> {
self.inner
.type_infos
.iter()
.filter_map(TypeInfo::object_type)
.map(|obj_type| EntityType::new(self.cheap_clone(), obj_type.name))
.collect()
}
pub fn entity_fulltext_definitions(
&self,
entity: &str,
) -> Result<Vec<FulltextDefinition>, anyhow::Error> {
Self::fulltext_definitions(&self.inner.schema.document, entity)
}
fn fulltext_definitions(
document: &s::Document,
entity: &str,
) -> Result<Vec<FulltextDefinition>, anyhow::Error> {
Ok(document
.get_fulltext_directives()?
.into_iter()
.filter(|directive| match directive.argument("include") {
Some(Value::List(includes)) if !includes.is_empty() => {
includes.iter().any(|include| match include {
Value::Object(include) => match include.get("entity") {
Some(Value::String(fulltext_entity)) if fulltext_entity == entity => {
true
}
_ => false,
},
_ => false,
})
}
_ => false,
})
.map(FulltextDefinition::from)
.collect())
}
pub fn id(&self) -> &DeploymentHash {
&self.inner.schema.id
}
pub fn document_string(&self) -> String {
self.inner.schema.document.to_string()
}
pub fn get_fulltext_directives(&self) -> Result<Vec<&s::Directive>, Error> {
self.inner.schema.document.get_fulltext_directives()
}
pub fn make_entity<I: IntoEntityIterator>(
&self,
iter: I,
) -> Result<Entity, EntityValidationError> {
Entity::make(self.inner.pool.clone(), iter)
}
pub fn try_make_entity<
E: std::error::Error + Send + Sync + 'static,
I: TryIntoEntityIterator<E>,
>(
&self,
iter: I,
) -> Result<Entity, Error> {
Entity::try_make(self.inner.pool.clone(), iter)
}
/// Check if `entity_type` is an object type and has a field `field`
pub(in crate::schema) fn has_field(&self, entity_type: Atom, field: Atom) -> bool {
self.type_info(entity_type)
.map(|ti| ti.kind.is_object() && ti.fields.contains(&field))
.unwrap_or(false)
}
pub fn poi_type(&self) -> EntityType {
// unwrap: we make sure to put POI_OBJECT into the pool
let atom = self.inner.pool.lookup(POI_OBJECT).unwrap();
EntityType::new(self.cheap_clone(), atom)
}
pub fn poi_digest(&self) -> Word {
Word::from(POI_DIGEST)
}
// A helper for the `EntityType` constructor
pub(in crate::schema) fn pool(&self) -> &Arc<AtomPool> {
&self.inner.pool
}
/// Return the entity type for `named`. If the entity type does not
/// exist, return an error. Generally, an error should only be possible
/// if `named` is based on user input. If `named` is an internal object,
/// like a `ObjectType`, it is safe to unwrap the result
pub fn entity_type<N: AsEntityTypeName>(&self, named: N) -> Result<EntityType, Error> {
let name = named.name();
self.inner
.pool
.lookup(name)
.and_then(|atom| self.type_info(atom).ok())
.map(|ti| EntityType::new(self.cheap_clone(), ti.name()))
.ok_or_else(|| {
anyhow!(
"internal error: entity type `{}` does not exist in {}",
name,
self.inner.schema.id
)
})
}
pub fn has_field_with_name(&self, entity_type: &EntityType, field: &str) -> bool {
let field = self.inner.pool.lookup(field);
match field {
Some(field) => self.has_field(entity_type.atom, field),
None => false,
}
}
}
/// Create a new pool that contains the names of all the types defined
/// in the document and the names of all their fields
fn atom_pool(document: &s::Document) -> AtomPool {
let mut pool = AtomPool::new();
pool.intern(&*ID);
pool.intern(POI_OBJECT); // Name of PoI entity type
pool.intern(POI_DIGEST); // Attribute of PoI object
for definition in &document.definitions {
match definition {
s::Definition::TypeDefinition(typedef) => match typedef {
s::TypeDefinition::Object(t) => {
pool.intern(&t.name);
for field in &t.fields {
pool.intern(&field.name);
}
}
s::TypeDefinition::Enum(t) => {
pool.intern(&t.name);
}
s::TypeDefinition::Interface(t) => {
pool.intern(&t.name);
for field in &t.fields {
pool.intern(&field.name);
}
}
s::TypeDefinition::InputObject(input_object) => {
pool.intern(&input_object.name);
for field in &input_object.fields {
pool.intern(&field.name);
}
}
s::TypeDefinition::Scalar(scalar_type) => {
pool.intern(&scalar_type.name);
}
s::TypeDefinition::Union(union_type) => {
pool.intern(&union_type.name);
for typ in &union_type.types {
pool.intern(typ);
}
}
},
s::Definition::SchemaDefinition(_)
| s::Definition::TypeExtension(_)
| s::Definition::DirectiveDefinition(_) => { /* ignore, these only happen for introspection schemas */
}
}
}
for object_type in document.get_object_type_definitions() {
for defn in InputSchema::fulltext_definitions(&document, &object_type.name).unwrap() {
pool.intern(defn.name.as_str());
}
}
pool
}
/// Validations for an `InputSchema`.
mod validations {
use std::{collections::HashSet, str::FromStr};
use inflector::Inflector;
use itertools::Itertools;
use crate::{
data::{
graphql::{
ext::DirectiveFinder, DirectiveExt, DocumentExt, ObjectTypeExt, TypeExt, ValueExt,
},
store::{IdType, ValueType, ID},
},
prelude::s,
schema::{
FulltextAlgorithm, FulltextLanguage, Schema as BaseSchema, SchemaValidationError,
Strings, SCHEMA_TYPE_NAME,
},
};
/// Helper struct for validations
struct Schema<'a> {
schema: &'a BaseSchema,
subgraph_schema_type: Option<&'a s::ObjectType>,
// All entity types, excluding the subgraph schema type
entity_types: Vec<&'a s::ObjectType>,
}
pub(super) fn validate(schema: &BaseSchema) -> Result<(), Vec<SchemaValidationError>> {
let schema = Schema::new(schema);
let mut errors: Vec<SchemaValidationError> = [
schema.validate_no_extra_types(),
schema.validate_derived_from(),
schema.validate_schema_type_has_no_fields(),
schema.validate_directives_on_schema_type(),
schema.validate_reserved_types_usage(),
schema.validate_interface_id_type(),
]
.into_iter()
.filter(Result::is_err)
// Safe unwrap due to the filter above
.map(Result::unwrap_err)
.collect();
errors.append(&mut schema.validate_entity_type_ids());
errors.append(&mut schema.validate_fields());
errors.append(&mut schema.validate_fulltext_directives());
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
impl<'a> Schema<'a> {
fn new(schema: &'a BaseSchema) -> Self {
let subgraph_schema_type = schema.subgraph_schema_object_type();
let mut entity_types = schema.document.get_object_type_definitions();
entity_types.retain(|obj_type| obj_type.name != SCHEMA_TYPE_NAME);
Schema {
schema,
subgraph_schema_type,
entity_types,
}
}
fn validate_schema_type_has_no_fields(&self) -> Result<(), SchemaValidationError> {
match self.subgraph_schema_type.and_then(|subgraph_schema_type| {
if !subgraph_schema_type.fields.is_empty() {
Some(SchemaValidationError::SchemaTypeWithFields)
} else {
None
}
}) {
Some(err) => Err(err),
None => Ok(()),
}
}
fn validate_directives_on_schema_type(&self) -> Result<(), SchemaValidationError> {
match self.subgraph_schema_type.and_then(|subgraph_schema_type| {
if subgraph_schema_type
.directives
.iter()
.filter(|directive| !directive.name.eq("fulltext"))
.next()
.is_some()
{
Some(SchemaValidationError::InvalidSchemaTypeDirectives)
} else {
None
}
}) {
Some(err) => Err(err),
None => Ok(()),
}
}
fn validate_fulltext_directives(&self) -> Vec<SchemaValidationError> {
self.subgraph_schema_type
.map_or(vec![], |subgraph_schema_type| {
subgraph_schema_type
.directives
.iter()
.filter(|directives| directives.name.eq("fulltext"))
.fold(vec![], |mut errors, fulltext| {
errors.extend(self.validate_fulltext_directive_name(fulltext));
errors.extend(self.validate_fulltext_directive_language(fulltext));
errors.extend(self.validate_fulltext_directive_algorithm(fulltext));
errors.extend(self.validate_fulltext_directive_includes(fulltext));
errors
})
})
}
fn validate_fulltext_directive_name(
&self,
fulltext: &s::Directive,
) -> Vec<SchemaValidationError> {
let name = match fulltext.argument("name") {
Some(s::Value::String(name)) => name,
_ => return vec![SchemaValidationError::FulltextNameUndefined],
};
// Validate that the fulltext field doesn't collide with any top-level Query fields
// generated for entity types. The field name conversions should always align with those used
// to create the field names in `graphql::schema::api::query_fields_for_type()`.
if self.entity_types.iter().any(|typ| {
typ.fields.iter().any(|field| {
name == &field.name.as_str().to_camel_case()
|| name == &field.name.to_plural().to_camel_case()
|| field.name.eq(name)
})
}) {
return vec![SchemaValidationError::FulltextNameCollision(
name.to_string(),
)];
}
// Validate that each fulltext directive has a distinct name
if self
.subgraph_schema_type
.unwrap()
.directives
.iter()
.filter(|directive| directive.name.eq("fulltext"))
.filter_map(|fulltext| {
// Collect all @fulltext directives with the same name
match fulltext.argument("name") {
Some(s::Value::String(n)) if name.eq(n) => Some(n.as_str()),
_ => None,
}
})
.count()