-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathmod.rs
More file actions
3258 lines (2972 loc) · 121 KB
/
mod.rs
File metadata and controls
3258 lines (2972 loc) · 121 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::ops::Range;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use anyhow::{anyhow, Error};
use semver::Version;
use store::Entity;
use crate::bail;
use crate::blockchain::BlockTime;
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::subgraph::SPEC_VERSION_1_3_0;
use crate::data::value::Word;
use crate::derive::CheapClone;
use crate::prelude::q::Value;
use crate::prelude::{s, DeploymentHash};
use crate::schema::api::api_schema;
use crate::util::intern::{Atom, AtomPool};
use crate::schema::fulltext::FulltextDefinition;
use crate::schema::{ApiSchema, AsEntityTypeName, EntityType, Schema};
pub mod sqlexpr;
/// 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 name of the PoI attribute for storing the block time
const POI_BLOCK_TIME: &str = "blockTime";
pub(crate) const VID_FIELD: &str = "vid";
pub mod kw {
pub const ENTITY: &str = "entity";
pub const IMMUTABLE: &str = "immutable";
pub const TIMESERIES: &str = "timeseries";
pub const TIMESTAMP: &str = "timestamp";
pub const AGGREGATE: &str = "aggregate";
pub const AGGREGATION: &str = "aggregation";
pub const SOURCE: &str = "source";
pub const FUNC: &str = "fn";
pub const ARG: &str = "arg";
pub const INTERVALS: &str = "intervals";
pub const INTERVAL: &str = "interval";
pub const CUMULATIVE: &str = "cumulative";
}
/// 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, CheapClone, Debug, PartialEq)]
pub struct InputSchema {
inner: Arc<Inner>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TypeKind {
/// The type is a normal @entity
Object,
/// The type is an interface
Interface,
/// The type is an aggregation
Aggregation,
}
#[derive(Debug, PartialEq)]
enum TypeInfo {
Object(ObjectType),
Interface(InterfaceType),
Aggregation(Aggregation),
}
impl TypeInfo {
fn is_object(&self) -> bool {
match self {
TypeInfo::Object(_) => true,
TypeInfo::Interface(_) | TypeInfo::Aggregation(_) => false,
}
}
fn is_interface(&self) -> bool {
match self {
TypeInfo::Object(_) | TypeInfo::Aggregation(_) => false,
TypeInfo::Interface(_) => true,
}
}
fn id_type(&self) -> Option<IdType> {
match self {
TypeInfo::Object(obj_type) => Some(obj_type.id_type),
TypeInfo::Interface(intf_type) => Some(intf_type.id_type),
TypeInfo::Aggregation(agg_type) => Some(agg_type.id_type),
}
}
fn fields(&self) -> &[Field] {
match self {
TypeInfo::Object(obj_type) => &obj_type.fields,
TypeInfo::Interface(intf_type) => &intf_type.fields,
TypeInfo::Aggregation(agg_type) => &agg_type.fields,
}
}
fn name(&self) -> Atom {
match self {
TypeInfo::Object(obj_type) => obj_type.name,
TypeInfo::Interface(intf_type) => intf_type.name,
TypeInfo::Aggregation(agg_type) => agg_type.name,
}
}
fn is_immutable(&self) -> bool {
match self {
TypeInfo::Object(obj_type) => obj_type.immutable,
TypeInfo::Interface(_) => false,
TypeInfo::Aggregation(_) => true,
}
}
fn kind(&self) -> TypeKind {
match self {
TypeInfo::Object(_) => TypeKind::Object,
TypeInfo::Interface(_) => TypeKind::Interface,
TypeInfo::Aggregation(_) => TypeKind::Aggregation,
}
}
fn object_type(&self) -> Option<&ObjectType> {
match self {
TypeInfo::Object(obj_type) => Some(obj_type),
TypeInfo::Interface(_) | TypeInfo::Aggregation(_) => None,
}
}
fn interface_type(&self) -> Option<&InterfaceType> {
match self {
TypeInfo::Interface(intf_type) => Some(intf_type),
TypeInfo::Object(_) | TypeInfo::Aggregation(_) => None,
}
}
fn aggregation(&self) -> Option<&Aggregation> {
match self {
TypeInfo::Aggregation(agg_type) => Some(agg_type),
TypeInfo::Interface(_) | TypeInfo::Object(_) => None,
}
}
}
impl TypeInfo {
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());
TypeInfo::Object(object_type)
}
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);
TypeInfo::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
TypeInfo::Object(ObjectType::for_poi(pool))
}
fn for_aggregation(schema: &Schema, pool: &AtomPool, agg_type: &s::ObjectType) -> Self {
let agg_type = Aggregation::new(&schema, &pool, agg_type);
TypeInfo::Aggregation(agg_type)
}
fn interfaces(&self) -> impl Iterator<Item = &str> {
const NO_INTF: [Word; 0] = [];
let interfaces = match &self {
TypeInfo::Object(obj_type) => &obj_type.interfaces,
TypeInfo::Interface(_) | TypeInfo::Aggregation(_) => NO_INTF.as_slice(),
};
interfaces.iter().map(|interface| interface.as_str())
}
}
#[derive(PartialEq, Debug, Clone)]
pub struct Field {
pub name: Word,
pub field_type: s::Type,
pub value_type: ValueType,
derived_from: Option<Word>,
}
impl Field {
pub fn new(
schema: &Schema,
name: &str,
field_type: &s::Type,
derived_from: Option<Word>,
) -> Self {
let value_type = Self::scalar_value_type(&schema, field_type);
Self {
name: Word::from(name),
field_type: field_type.clone(),
value_type,
derived_from,
}
}
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),
}
}
pub fn is_list(&self) -> bool {
self.field_type.is_list()
}
pub fn derived_from<'a>(&self, schema: &'a InputSchema) -> Option<&'a Field> {
let derived_from = self.derived_from.as_ref()?;
let name = schema
.pool()
.lookup(&self.field_type.get_base_type())
.unwrap();
schema.field(name, derived_from)
}
pub fn is_derived(&self) -> bool {
self.derived_from.is_some()
}
}
#[derive(Copy, Clone)]
pub enum ObjectOrInterface<'a> {
Object(&'a InputSchema, &'a ObjectType),
Interface(&'a InputSchema, &'a InterfaceType),
}
impl<'a> CheapClone for ObjectOrInterface<'a> {
fn cheap_clone(&self) -> Self {
match self {
ObjectOrInterface::Object(schema, object) => {
ObjectOrInterface::Object(*schema, *object)
}
ObjectOrInterface::Interface(schema, interface) => {
ObjectOrInterface::Interface(*schema, *interface)
}
}
}
}
impl<'a> ObjectOrInterface<'a> {
pub fn object_types(self) -> Vec<EntityType> {
let (schema, object_types) = match self {
ObjectOrInterface::Object(schema, object) => (schema, vec![object]),
ObjectOrInterface::Interface(schema, interface) => {
(schema, schema.implementers(interface).collect())
}
};
object_types
.into_iter()
.map(|object_type| EntityType::new(schema.cheap_clone(), object_type.name))
.collect()
}
pub fn typename(&self) -> &str {
let (schema, atom) = self.unpack();
schema.pool().get(atom).unwrap()
}
/// Return the field with the given name. For interfaces, that is the
/// field with that name declared in the interface, not in the
/// implementing object types
pub fn field(&self, name: &str) -> Option<&Field> {
match self {
ObjectOrInterface::Object(_, object) => object.field(name),
ObjectOrInterface::Interface(_, interface) => interface.field(name),
}
}
/// Return the field with the given name. For object types, that's the
/// field with that name. For interfaces, it's the field with that name
/// in the first object type that implements the interface; to be
/// useful, this tacitly assumes that all implementers of an interface
/// declare that field in the same way
pub fn implemented_field(&self, name: &str) -> Option<&Field> {
let object_type = match self {
ObjectOrInterface::Object(_, object_type) => Some(*object_type),
ObjectOrInterface::Interface(schema, interface) => {
schema.implementers(&interface).next()
}
};
object_type.and_then(|object_type| object_type.field(name))
}
pub fn is_interface(&self) -> bool {
match self {
ObjectOrInterface::Object(_, _) => false,
ObjectOrInterface::Interface(_, _) => true,
}
}
pub fn derived_from(&self, field_name: &str) -> Option<&str> {
let field = self.field(field_name)?;
field.derived_from.as_ref().map(|name| name.as_str())
}
pub fn entity_type(&self) -> EntityType {
let (schema, atom) = self.unpack();
EntityType::new(schema.cheap_clone(), atom)
}
fn unpack(&self) -> (&InputSchema, Atom) {
match self {
ObjectOrInterface::Object(schema, object) => (schema, object.name),
ObjectOrInterface::Interface(schema, interface) => (schema, interface.name),
}
}
pub fn is_aggregation(&self) -> bool {
match self {
ObjectOrInterface::Object(_, object) => object.is_aggregation(),
ObjectOrInterface::Interface(_, _) => false,
}
}
}
impl std::fmt::Debug for ObjectOrInterface<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let (schema, name) = match self {
ObjectOrInterface::Object(schema, object) => (schema, object.name),
ObjectOrInterface::Interface(schema, interface) => (schema, interface.name),
};
write!(f, "ObjectOrInterface({})", schema.pool().get(name).unwrap())
}
}
#[derive(PartialEq, Debug)]
pub struct ObjectType {
pub name: Atom,
pub id_type: IdType,
pub fields: Box<[Field]>,
pub immutable: bool,
/// The name of the aggregation to which this object type belongs if it
/// is part of an aggregation
aggregation: Option<Atom>,
pub timeseries: bool,
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 derived_from = field.derived_from().map(|name| Word::from(name));
Field::new(schema, &field.name, &field.field_type, derived_from)
})
.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");
let dir = object_type.find_directive("entity").unwrap();
let timeseries = match dir.argument("timeseries") {
Some(Value::Boolean(ts)) => *ts,
None => false,
_ => unreachable!("validations ensure we don't get here"),
};
let immutable = match dir.argument("immutable") {
Some(Value::Boolean(im)) => *im,
None => timeseries,
_ => unreachable!("validations ensure we don't get here"),
};
Self {
name,
fields,
id_type,
immutable,
aggregation: None,
timeseries,
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,
derived_from: None,
},
Field {
name: Word::from(POI_DIGEST),
field_type: s::Type::NamedType("String".to_string()),
value_type: ValueType::String,
derived_from: None,
},
]
.into_boxed_slice();
let name = pool
.lookup(POI_OBJECT)
.expect("POI_OBJECT has been interned");
Self {
name,
interfaces: Box::new([]),
id_type: IdType::String,
immutable: false,
aggregation: None,
timeseries: false,
fields,
shared_interfaces: Box::new([]),
}
}
pub fn field(&self, name: &str) -> Option<&Field> {
self.fields.iter().find(|field| field.name == name)
}
/// Return `true` if this object type is part of an aggregation
pub fn is_aggregation(&self) -> bool {
self.aggregation.is_some()
}
}
#[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: Box<[Field]>,
implementers: Box<[Atom]>,
}
impl InterfaceType {
fn new(
schema: &Schema,
pool: &AtomPool,
interface_type: &s::InterfaceType,
implementers: &[s::ObjectType],
) -> Self {
let fields = interface_type
.fields
.iter()
.map(|field| {
// It's very unclear what it means for an interface field to
// be derived; but for legacy reasons, we need to allow it
// since the API schema does not contain certain filters for
// derived fields on interfaces that it would for
// non-derived fields
let derived_from = field.derived_from().map(|name| Word::from(name));
Field::new(schema, &field.name, &field.field_type, derived_from)
})
.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);
let implementers = implementers
.iter()
.map(|obj_type| {
pool.lookup(&obj_type.name)
.expect("object type names have been interned")
})
.collect();
Self {
name,
id_type,
fields,
implementers,
}
}
fn field(&self, name: &str) -> Option<&Field> {
self.fields.iter().find(|field| field.name == name)
}
}
#[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(PartialEq, Debug, Clone)]
pub enum AggregateFn {
Sum,
Max,
Min,
Count,
First,
Last,
}
impl FromStr for AggregateFn {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"sum" => Ok(AggregateFn::Sum),
"max" => Ok(AggregateFn::Max),
"min" => Ok(AggregateFn::Min),
"count" => Ok(AggregateFn::Count),
"first" => Ok(AggregateFn::First),
"last" => Ok(AggregateFn::Last),
_ => Err(anyhow!("invalid aggregate function `{}`", s)),
}
}
}
impl AggregateFn {
pub fn has_arg(&self) -> bool {
use AggregateFn::*;
match self {
Sum | Max | Min | First | Last => true,
Count => false,
}
}
fn as_str(&self) -> &'static str {
use AggregateFn::*;
match self {
Sum => "sum",
Max => "max",
Min => "min",
Count => "count",
First => "first",
Last => "last",
}
}
}
/// The supported intervals for timeseries in order of decreasing
/// granularity. The intervals must all be divisible by the smallest
/// interval
#[derive(Clone, Copy, PartialEq, Eq, Debug, PartialOrd, Ord, Hash)]
pub enum AggregationInterval {
Hour,
Day,
}
impl AggregationInterval {
pub fn as_str(&self) -> &'static str {
match self {
AggregationInterval::Hour => "hour",
AggregationInterval::Day => "day",
}
}
pub fn as_duration(&self) -> Duration {
use AggregationInterval::*;
match self {
Hour => Duration::from_secs(3600),
Day => Duration::from_secs(3600 * 24),
}
}
/// Return time ranges for all buckets that intersect `from..to` except
/// the last one. In other words, return time ranges for all buckets
/// that overlap `from..to` and end before `to`. The ranges are in
/// increasing order of the start time
pub fn buckets(&self, from: BlockTime, to: BlockTime) -> Vec<Range<BlockTime>> {
let first = from.bucket(self.as_duration());
let last = to.bucket(self.as_duration());
(first..last)
.map(|nr| self.as_duration() * nr as u32)
.map(|start| {
let lower = BlockTime::from(start);
let upper = BlockTime::from(start + self.as_duration());
lower..upper
})
.collect()
}
}
impl std::fmt::Display for AggregationInterval {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[test]
fn buckets() {
// 2006-07-16 07:40Z
const START: i64 = 1153035600;
// 2006-07-16 08:00Z, the start of the next hourly bucket after `START`
const EIGHT_AM: i64 = 1153036800;
let start = BlockTime::since_epoch(START, 0);
let seven_am = BlockTime::since_epoch(START - 40 * 60, 0);
let eight_am = BlockTime::since_epoch(EIGHT_AM, 0);
let nine_am = BlockTime::since_epoch(EIGHT_AM + 3600, 0);
// One hour and two hours after `START`
let one_hour = BlockTime::since_epoch(START + 3600, 0);
let two_hour = BlockTime::since_epoch(START + 2 * 3600, 0);
use AggregationInterval::*;
assert_eq!(vec![seven_am..eight_am], Hour.buckets(start, eight_am));
assert_eq!(vec![seven_am..eight_am], Hour.buckets(start, one_hour),);
assert_eq!(
vec![seven_am..eight_am, eight_am..nine_am],
Hour.buckets(start, two_hour),
);
assert_eq!(vec![eight_am..nine_am], Hour.buckets(one_hour, two_hour));
assert_eq!(Vec::<Range<BlockTime>>::new(), Day.buckets(start, two_hour));
}
impl FromStr for AggregationInterval {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"hour" => Ok(AggregationInterval::Hour),
"day" => Ok(AggregationInterval::Day),
_ => Err(anyhow!("invalid aggregation interval `{}`", s)),
}
}
}
/// The connection between the object type that stores the data points for
/// an aggregation and the type that stores the finalised aggregations.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct AggregationMapping {
pub interval: AggregationInterval,
// Index of aggregation type in `type_infos`
aggregation: usize,
// Index of the object type for the interval in the aggregation's `obj_types`
agg_type: usize,
}
impl AggregationMapping {
pub fn source_type(&self, schema: &InputSchema) -> EntityType {
let source = self.aggregation(schema).source;
EntityType::new(schema.cheap_clone(), source)
}
pub fn aggregation<'a>(&self, schema: &'a InputSchema) -> &'a Aggregation {
schema.inner.type_infos[self.aggregation]
.aggregation()
.expect("the aggregation source is an object type")
}
pub fn agg_type(&self, schema: &InputSchema) -> EntityType {
let agg_type = self.aggregation(schema).obj_types[self.agg_type].name;
EntityType::new(schema.cheap_clone(), agg_type)
}
}
/// The `@aggregate` annotation in an aggregation. The annotation controls
/// how values from the source table are aggregated
#[derive(PartialEq, Debug)]
pub struct Aggregate {
/// The name of the aggregate field in the aggregation
pub name: Word,
/// The function used to aggregate the values
pub func: AggregateFn,
/// The field to aggregate in the source table
pub arg: Word,
/// The type of the field `name` in the aggregation
pub field_type: s::Type,
/// The `ValueType` corresponding to `field_type`
pub value_type: ValueType,
/// Whether the aggregation is cumulative
pub cumulative: bool,
}
impl Aggregate {
fn new(_schema: &Schema, name: &str, field_type: &s::Type, dir: &s::Directive) -> Self {
let func = dir
.argument("fn")
.unwrap()
.as_str()
.unwrap()
.parse()
.unwrap();
// The only aggregation function we have that doesn't take an
// argument is `count`; we just pretend that the user wanted to
// `count(id)`. When we form a query, we ignore the argument for
// `count`
let arg = dir
.argument("arg")
.map(|arg| Word::from(arg.as_str().unwrap()))
.unwrap_or_else(|| ID.clone());
let cumulative = dir
.argument(kw::CUMULATIVE)
.map(|arg| match arg {
Value::Boolean(b) => *b,
_ => unreachable!("validation ensures this is a boolean"),
})
.unwrap_or(false);
Aggregate {
name: Word::from(name),
func,
arg,
cumulative,
field_type: field_type.clone(),
value_type: field_type.get_base_type().parse().unwrap(),
}
}
/// The field needed for the finalised aggregation for hourly/daily
/// values
pub fn as_agg_field(&self) -> Field {
Field {
name: self.name.clone(),
field_type: self.field_type.clone(),
value_type: self.value_type,
derived_from: None,
}
}
}
#[derive(PartialEq, Debug)]
pub struct Aggregation {
pub name: Atom,
pub id_type: IdType,
pub intervals: Box<[AggregationInterval]>,
pub source: Atom,
/// The non-aggregation fields of the time series
pub fields: Box<[Field]>,
pub aggregates: Box<[Aggregate]>,
/// The object types for the aggregated data, one for each interval, in
/// the same order as `intervals`
obj_types: Box<[ObjectType]>,
}
impl Aggregation {
pub fn new(schema: &Schema, pool: &AtomPool, agg_type: &s::ObjectType) -> Self {
let name = pool.lookup(&agg_type.name).unwrap();
let id_type = IdType::try_from(agg_type).expect("validation caught any issues here");
let intervals = Self::parse_intervals(agg_type).into_boxed_slice();
let source = agg_type
.find_directive(kw::AGGREGATION)
.unwrap()
.argument("source")
.unwrap()
.as_str()
.unwrap();
let source = pool.lookup(source).unwrap();
let fields: Box<[_]> = agg_type
.fields
.iter()
.filter(|field| field.find_directive(kw::AGGREGATE).is_none())
.map(|field| Field::new(schema, &field.name, &field.field_type, None))
.collect();
let aggregates: Box<[_]> = agg_type
.fields
.iter()
.filter_map(|field| field.find_directive(kw::AGGREGATE).map(|dir| (field, dir)))
.map(|(field, dir)| Aggregate::new(schema, &field.name, &field.field_type, dir))
.collect();
let obj_types = intervals
.iter()
.map(|interval| {
let name = format!("{}_{}", &agg_type.name, interval.as_str());
let name = pool.lookup(&name).unwrap();
ObjectType {
name,
id_type,
fields: fields
.iter()
.cloned()
.chain(aggregates.iter().map(Aggregate::as_agg_field))
.collect(),
immutable: true,
aggregation: Some(name),
timeseries: false,
interfaces: Box::new([]),
shared_interfaces: Box::new([]),
}
})
.collect();
Self {
name,
id_type,
intervals,
source,
fields,
aggregates,
obj_types,
}
}
fn parse_intervals(agg_type: &s::ObjectType) -> Vec<AggregationInterval> {
let dir = agg_type.find_directive(kw::AGGREGATION).unwrap();
let mut intervals: Vec<_> = dir
.argument(kw::INTERVALS)
.unwrap()
.as_list()
.unwrap()
.iter()
.map(|interval| interval.as_str().unwrap().parse().unwrap())
.collect();
intervals.sort();
intervals.dedup();
intervals
}
fn has_object_type(&self, atom: Atom) -> bool {
self.obj_types.iter().any(|obj_type| obj_type.name == atom)
}
fn aggregated_type(&self, atom: Atom) -> Option<&ObjectType> {
self.obj_types.iter().find(|obj_type| obj_type.name == atom)
}
pub fn dimensions(&self) -> impl Iterator<Item = &Field> {
self.fields
.iter()
.filter(|field| &field.name != &*ID && field.name != kw::TIMESTAMP)
}
fn object_type(&self, interval: AggregationInterval) -> Option<&ObjectType> {
let pos = self.intervals.iter().position(|i| *i == interval)?;
Some(&self.obj_types[pos])
}
fn field(&self, name: &str) -> Option<&Field> {
self.fields.iter().find(|field| field.name == name)
}
}
#[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>,
/// A list of all timeseries types by interval
agg_mappings: Box<[AggregationMapping]>,
spec_version: Version,
}
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(spec_version: &Version, raw: &str, id: DeploymentHash) -> Result<Self, Error> {
fn agg_mappings(ts_types: &[TypeInfo]) -> Box<[AggregationMapping]> {
let mut mappings: Vec<_> = ts_types
.iter()
.enumerate()
.filter_map(|(idx, ti)| ti.aggregation().map(|agg_type| (idx, agg_type)))
.map(|(aggregation, agg_type)| {
agg_type
.intervals
.iter()
.enumerate()
.map(move |(agg_type, interval)| AggregationMapping {
interval: *interval,
aggregation,
agg_type,
})
})
.flatten()
.collect();
mappings.sort();
mappings.into_boxed_slice()
}
let schema = Schema::parse(raw, id.clone())?;
validations::validate(spec_version, &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")
)