-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathwrite.rs
More file actions
1379 lines (1222 loc) · 44.1 KB
/
write.rs
File metadata and controls
1379 lines (1222 loc) · 44.1 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
//! Data structures and helpers for writing subgraph changes to the store
use std::{
collections::{HashMap, HashSet},
sync::Arc,
};
use slog::Logger;
use crate::{
blockchain::{block_stream::FirehoseCursor, BlockPtr, BlockTime},
cheap_clone::CheapClone,
components::subgraph::Entity,
data::{store::Id, subgraph::schema::SubgraphError},
data_source::CausalityRegion,
derive::CacheWeight,
env::ENV_VARS,
internal_error,
util::cache_weight::CacheWeight,
};
use super::{BlockNumber, EntityKey, EntityType, StoreError, StoredDynamicDataSource};
/// A data structure similar to `EntityModification`, but tagged with a
/// block. We might eventually replace `EntityModification` with this, but
/// until the dust settles, we'll keep them separate.
///
/// This is geared towards how we persist entity changes: there are only
/// ever two operations we perform on them, clamping the range of an
/// existing entity version, and writing a new entity version.
///
/// The difference between `Insert` and `Overwrite` is that `Overwrite`
/// requires that we clamp an existing prior version of the entity at
/// `block`. We only ever get an `Overwrite` if such a version actually
/// exists. `Insert` simply inserts a new row into the underlying table,
/// assuming that there is no need to fix up any prior version.
///
/// The `end` field for `Insert` and `Overwrite` indicates whether the
/// entity exists now: if it is `None`, the entity currently exists, but if
/// it is `Some(_)`, it was deleted, for example, by folding a `Remove` or
/// `Overwrite` into this operation. The entity version will only be visible
/// before `end`, excluding `end`. This folding, which happens in
/// `append_row`, eliminates an update in the database which would otherwise
/// be needed to clamp the open block range of the entity to the block
/// contained in `end`
#[derive(Clone, CacheWeight, Debug, PartialEq, Eq)]
pub enum EntityModification {
/// Insert the entity
Insert {
key: EntityKey,
data: Arc<Entity>,
block: BlockNumber,
end: Option<BlockNumber>,
},
/// Update the entity by overwriting it
Overwrite {
key: EntityKey,
data: Arc<Entity>,
block: BlockNumber,
end: Option<BlockNumber>,
},
/// Remove the entity
Remove { key: EntityKey, block: BlockNumber },
}
/// A helper struct for passing entity writes to the outside world, viz. the
/// SQL query generation that inserts rows
pub struct EntityWrite<'a> {
pub id: &'a Id,
pub entity: &'a Entity,
pub causality_region: CausalityRegion,
pub block: BlockNumber,
// The end of the block range for which this write is valid. The value
// of `end` itself is not included in the range
pub end: Option<BlockNumber>,
}
impl std::fmt::Display for EntityWrite<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let range = match self.end {
Some(end) => format!("[{}, {}]", self.block, end - 1),
None => format!("[{}, ∞)", self.block),
};
write!(f, "{}@{}", self.id, range)
}
}
impl<'a> TryFrom<&'a EntityModification> for EntityWrite<'a> {
type Error = ();
fn try_from(emod: &'a EntityModification) -> Result<Self, Self::Error> {
match emod {
EntityModification::Insert {
key,
data,
block,
end,
} => Ok(EntityWrite {
id: &key.entity_id,
entity: data,
causality_region: key.causality_region,
block: *block,
end: *end,
}),
EntityModification::Overwrite {
key,
data,
block,
end,
} => Ok(EntityWrite {
id: &key.entity_id,
entity: data,
causality_region: key.causality_region,
block: *block,
end: *end,
}),
EntityModification::Remove { .. } => Err(()),
}
}
}
impl EntityModification {
pub fn id(&self) -> &Id {
match self {
EntityModification::Insert { key, .. }
| EntityModification::Overwrite { key, .. }
| EntityModification::Remove { key, .. } => &key.entity_id,
}
}
fn block(&self) -> BlockNumber {
match self {
EntityModification::Insert { block, .. }
| EntityModification::Overwrite { block, .. }
| EntityModification::Remove { block, .. } => *block,
}
}
/// Return `true` if `self` requires a write operation, i.e.,insert of a
/// new row, for either a new or an existing entity
fn is_write(&self) -> bool {
match self {
EntityModification::Insert { .. } | EntityModification::Overwrite { .. } => true,
EntityModification::Remove { .. } => false,
}
}
/// Return the details of the write if `self` is a write operation for a
/// new or an existing entity
fn as_write(&self) -> Option<EntityWrite<'_>> {
EntityWrite::try_from(self).ok()
}
/// Return `true` if `self` requires clamping of an existing version
fn is_clamp(&self) -> bool {
match self {
EntityModification::Insert { .. } => false,
EntityModification::Overwrite { .. } | EntityModification::Remove { .. } => true,
}
}
pub fn creates_entity(&self) -> bool {
use EntityModification::*;
match self {
Insert { .. } => true,
Overwrite { .. } | Remove { .. } => false,
}
}
fn entity_count_change(&self) -> i32 {
match self {
EntityModification::Insert { end: None, .. } => 1,
EntityModification::Insert { end: Some(_), .. } => {
// Insert followed by a remove
0
}
EntityModification::Overwrite { end: None, .. } => 0,
EntityModification::Overwrite { end: Some(_), .. } => {
// Overwrite followed by a remove
-1
}
EntityModification::Remove { .. } => -1,
}
}
fn clamp(&mut self, block: BlockNumber) -> Result<(), StoreError> {
use EntityModification::*;
match self {
Insert { end, .. } | Overwrite { end, .. } => {
if end.is_some() {
return Err(internal_error!(
"can not clamp {:?} to block {}",
self,
block
));
}
*end = Some(block);
}
Remove { .. } => {
return Err(internal_error!(
"can not clamp block range for removal of {:?} to {}",
self,
block
))
}
}
Ok(())
}
/// Turn an `Overwrite` into an `Insert`, return an error if this is a `Remove`
fn into_insert(self, entity_type: &EntityType) -> Result<Self, StoreError> {
use EntityModification::*;
match self {
Insert { .. } => Ok(self),
Overwrite {
key,
data,
block,
end,
} => Ok(Insert {
key,
data,
block,
end,
}),
Remove { key, .. } => Err(internal_error!(
"a remove for {}[{}] can not be converted into an insert",
entity_type,
key.entity_id
)),
}
}
fn as_entity_op(&self, at: BlockNumber) -> EntityOp<'_> {
debug_assert!(self.block() <= at);
use EntityModification::*;
match self {
Insert {
data,
key,
end: None,
..
}
| Overwrite {
data,
key,
end: None,
..
} => EntityOp::Write { key, entity: data },
Insert {
data,
key,
end: Some(end),
..
}
| Overwrite {
data,
key,
end: Some(end),
..
} if at < *end => EntityOp::Write { key, entity: data },
Insert {
key, end: Some(_), ..
}
| Overwrite {
key, end: Some(_), ..
}
| Remove { key, .. } => EntityOp::Remove { key },
}
}
}
impl EntityModification {
pub fn insert(key: EntityKey, data: Entity, block: BlockNumber) -> Self {
EntityModification::Insert {
key,
data: Arc::new(data),
block,
end: None,
}
}
pub fn overwrite(key: EntityKey, data: Entity, block: BlockNumber) -> Self {
EntityModification::Overwrite {
key,
data: Arc::new(data),
block,
end: None,
}
}
pub fn remove(key: EntityKey, block: BlockNumber) -> Self {
EntityModification::Remove { key, block }
}
pub fn key(&self) -> &EntityKey {
use EntityModification::*;
match self {
Insert { key, .. } | Overwrite { key, .. } | Remove { key, .. } => key,
}
}
}
/// A map from entity ids to the index of the last modification for that id.
/// If `ENV_VARS.store.write_batch_memoize` is `false`, this map is never
/// written to and always empty
#[derive(Debug, CacheWeight)]
struct LastMod {
/// If `ENV_VARS.store.write_batch_memoize` is `false`, we never write
/// into this map
map: HashMap<Id, usize>,
}
impl LastMod {
fn new() -> LastMod {
LastMod {
map: HashMap::new(),
}
}
fn get(&self, id: &Id) -> Option<&usize> {
if ENV_VARS.store.write_batch_memoize {
return self.map.get(id);
}
None
}
fn insert(&mut self, id: Id, idx: usize) {
if ENV_VARS.store.write_batch_memoize {
self.map.insert(id, idx);
}
}
}
/// A list of entity changes grouped by the entity type
#[derive(Debug, CacheWeight)]
pub struct RowGroup {
pub entity_type: EntityType,
/// All changes for this entity type, ordered by block; i.e., if `i < j`
/// then `rows[i].block() <= rows[j].block()`. Several methods on this
/// struct rely on the fact that this ordering is observed.
rows: Vec<EntityModification>,
/// Map the `key.entity_id` of all entries in `rows` to the index with
/// the most recent entry for that id to speed up lookups.
last_mod: LastMod,
}
impl RowGroup {
pub fn new(entity_type: EntityType) -> Self {
Self {
entity_type,
rows: Vec::new(),
last_mod: LastMod::new(),
}
}
pub fn push(&mut self, emod: EntityModification, block: BlockNumber) -> Result<(), StoreError> {
let is_forward = self
.rows
.last()
.map(|emod| emod.block() <= block)
.unwrap_or(true);
if !is_forward {
// unwrap: we only get here when `last()` is `Some`
let last_block = self.rows.last().map(|emod| emod.block()).unwrap();
return Err(internal_error!(
"we already have a modification for block {}, can not append {:?}",
last_block,
emod
));
}
self.append_row(emod)
}
fn row_count(&self) -> usize {
self.rows.len()
}
/// Return the change in entity count that will result from applying
/// writing this row group to the database
pub fn entity_count_change(&self) -> i32 {
self.rows.iter().map(|row| row.entity_count_change()).sum()
}
/// Iterate over all changes that need clamping of the block range of an
/// existing entity version
pub fn clamps_by_block(&self) -> impl Iterator<Item = (BlockNumber, &[EntityModification])> {
ClampsByBlockIterator::new(self)
}
/// Iterate over all changes that require writing a new entity version
pub fn writes(&self) -> impl Iterator<Item = &EntityModification> {
self.rows.iter().filter(|row| row.is_write())
}
/// Return an iterator over all writes in chunks. The returned
/// `WriteChunker` is an iterator that produces `WriteChunk`s, which are
/// the iterators over the writes. Each `WriteChunk` has `chunk_size`
/// elements, except for the last one which might have fewer
pub fn write_chunks<'a>(&'a self, chunk_size: usize) -> WriteChunker<'a> {
WriteChunker::new(self, chunk_size)
}
pub fn has_clamps(&self) -> bool {
self.rows.iter().any(|row| row.is_clamp())
}
pub fn last_op(&self, key: &EntityKey, at: BlockNumber) -> Option<EntityOp<'_>> {
// If we have `key` in `last_mod`, use that and return the
// corresponding op. If not, fall through to a more expensive search
if let Some(&idx) = self.last_mod.get(&key.entity_id) {
if let Some(op) = self.rows.get(idx).and_then(|emod| {
if emod.block() <= at {
Some(emod.as_entity_op(at))
} else {
None
}
}) {
return Some(op);
}
}
// We are looking for the change at a block `at` that is before the
// change we remember in `last_mod`, and therefore have to scan
// through all changes
self.rows
.iter()
// We are scanning backwards, i.e., in descendng order of
// `emod.block()`. Therefore, the first `emod` we encounter
// whose block is before `at` is the one in effect
.rfind(|emod| emod.key() == key && emod.block() <= at)
.map(|emod| emod.as_entity_op(at))
}
/// Return an iterator over all changes that are effective at `at`. That
/// makes it possible to construct the state that the deployment will
/// have once all changes for block `at` have been written.
pub fn effective_ops(&self, at: BlockNumber) -> impl Iterator<Item = EntityOp<'_>> {
// We don't use `self.last_mod` here, because we need to return
// operations for all entities that have pending changes at block
// `at`, and there is no guarantee that `self.last_mod` is visible
// at `at` since the change in `self.last_mod` might come after `at`
let mut seen = HashSet::new();
self.rows
.iter()
.rev()
.filter(move |emod| {
if emod.block() <= at {
seen.insert(emod.id())
} else {
false
}
})
.map(move |emod| emod.as_entity_op(at))
}
/// Find the most recent entry for `id`
fn prev_row_mut(&mut self, id: &Id) -> Option<&mut EntityModification> {
if let Some(&idx) = self.last_mod.get(id) {
return self.rows.get_mut(idx);
}
self.rows.iter_mut().rfind(|emod| emod.id() == id)
}
/// Append `row` to `self.rows` by combining it with a previously
/// existing row, if that is possible
fn append_row(&mut self, row: EntityModification) -> Result<(), StoreError> {
if self.entity_type.is_immutable() {
match row {
EntityModification::Insert { .. } => {
// Check if this is an attempt to overwrite an immutable
// entity. We allow overwriting immutable entities in
// the same block, but not across blocks; if such an
// attempt happens across two batches, it would result
// in a database constraint violation. This check is
// simply here to provide a friendlier error message and
// to raise the error earlier, before we actually write
// to the database
match self
.last_mod
.get(row.id())
.and_then(|&idx| self.rows.get(idx))
{
Some(prev) if prev.block() != row.block() => {
if self.entity_type.skip_duplicates() {
return Ok(());
}
return Err(StoreError::Input(
format!("entity {} is immutable; inserting it at block {} is not possible as it was already inserted at block {}",
row.key(), row.block(), prev.block())));
}
_ => { /* nothing to check */ }
}
self.push_row(row);
}
EntityModification::Overwrite { .. } | EntityModification::Remove { .. } => {
if self.entity_type.skip_duplicates() {
return Ok(());
}
return Err(internal_error!(
"immutable entity type {} only allows inserts, not {:?}",
self.entity_type,
row
));
}
}
return Ok(());
}
if let Some(prev_row) = self.prev_row_mut(row.id()) {
use EntityModification::*;
if row.block() <= prev_row.block() {
return Err(internal_error!(
"can not append operations that go backwards from {:?} to {:?}",
prev_row,
row
));
}
if row.id() != prev_row.id() {
return Err(internal_error!(
"last_mod map is corrupted: got id {} looking up id {}",
prev_row.id(),
row.id()
));
}
// The heart of the matter: depending on what `row` is, clamp
// `prev_row` and either ignore `row` since it is not needed, or
// turn it into an `Insert`, which also does not require
// clamping an old version
match (&*prev_row, &row) {
(Insert { end: None, .. } | Overwrite { end: None, .. }, Insert { .. })
| (Remove { .. }, Overwrite { .. })
| (
Insert { end: Some(_), .. } | Overwrite { end: Some(_), .. },
Overwrite { .. } | Remove { .. },
) => {
return Err(internal_error!(
"impossible combination of entity operations: {:?} and then {:?}",
prev_row,
row
))
}
(Remove { .. }, Remove { .. }) => {
// Ignore the new row, since prev_row is already a
// delete. This can happen when subgraphs delete
// entities without checking if they even exist
}
(
Insert { end: Some(_), .. } | Overwrite { end: Some(_), .. } | Remove { .. },
Insert { .. },
) => {
// prev_row was deleted
self.push_row(row);
}
(
Insert { end: None, .. } | Overwrite { end: None, .. },
Overwrite { block, .. },
) => {
prev_row.clamp(*block)?;
let row = row.into_insert(&self.entity_type)?;
self.push_row(row);
}
(Insert { end: None, .. } | Overwrite { end: None, .. }, Remove { block, .. }) => {
prev_row.clamp(*block)?;
}
}
} else {
self.push_row(row);
}
Ok(())
}
fn push_row(&mut self, row: EntityModification) {
self.last_mod.insert(row.id().clone(), self.rows.len());
self.rows.push(row);
}
fn append(&mut self, group: RowGroup) -> Result<(), StoreError> {
if self.entity_type != group.entity_type {
return Err(internal_error!(
"Can not append a row group for {} to a row group for {}",
group.entity_type,
self.entity_type
));
}
self.rows.reserve(group.rows.len());
for row in group.rows {
self.append_row(row)?;
}
Ok(())
}
pub fn ids(&self) -> impl Iterator<Item = &Id> {
self.rows.iter().map(|emod| emod.id())
}
}
pub struct RowGroupForPerfTest(RowGroup);
impl RowGroupForPerfTest {
pub fn new(entity_type: EntityType) -> Self {
Self(RowGroup::new(entity_type))
}
pub fn push(&mut self, emod: EntityModification, block: BlockNumber) -> Result<(), StoreError> {
self.0.push(emod, block)
}
pub fn append_row(&mut self, row: EntityModification) -> Result<(), StoreError> {
self.0.append_row(row)
}
}
struct ClampsByBlockIterator<'a> {
position: usize,
rows: &'a [EntityModification],
}
impl<'a> ClampsByBlockIterator<'a> {
fn new(group: &'a RowGroup) -> Self {
ClampsByBlockIterator {
position: 0,
rows: &group.rows,
}
}
}
impl<'a> Iterator for ClampsByBlockIterator<'a> {
type Item = (BlockNumber, &'a [EntityModification]);
fn next(&mut self) -> Option<Self::Item> {
// Make sure we start on a clamp
while self.position < self.rows.len() && !self.rows[self.position].is_clamp() {
self.position += 1;
}
if self.position >= self.rows.len() {
return None;
}
let block = self.rows[self.position].block();
let mut next = self.position;
// Collect consecutive clamps
while next < self.rows.len()
&& self.rows[next].block() == block
&& self.rows[next].is_clamp()
{
next += 1;
}
let res = Some((block, &self.rows[self.position..next]));
self.position = next;
res
}
}
/// A list of entity changes with one group per entity type
#[derive(Debug, CacheWeight)]
pub struct RowGroups {
pub groups: Vec<RowGroup>,
logger: Logger,
}
impl RowGroups {
fn new(logger: Logger) -> Self {
Self {
groups: Vec::new(),
logger,
}
}
fn group(&self, entity_type: &EntityType) -> Option<&RowGroup> {
self.groups
.iter()
.find(|group| &group.entity_type == entity_type)
}
/// Return a mutable reference to an existing group, or create a new one
/// if there isn't one yet and return a reference to that
fn group_entry(&mut self, entity_type: &EntityType) -> &mut RowGroup {
let pos = self
.groups
.iter()
.position(|group| &group.entity_type == entity_type);
match pos {
Some(pos) => &mut self.groups[pos],
None => {
self.groups.push(RowGroup::new(entity_type.clone()));
// unwrap: we just pushed an entry
self.groups.last_mut().unwrap()
}
}
}
fn entity_count(&self) -> usize {
self.groups.iter().map(|group| group.row_count()).sum()
}
fn append(&mut self, other: RowGroups) -> Result<(), StoreError> {
for group in other.groups {
self.group_entry(&group.entity_type).append(group)?;
}
Ok(())
}
}
/// Data sources data grouped by block
#[derive(Debug)]
pub struct DataSources {
pub entries: Vec<(BlockPtr, Vec<StoredDynamicDataSource>)>,
}
impl DataSources {
fn new(ptr: BlockPtr, entries: Vec<StoredDynamicDataSource>) -> Self {
let entries = if entries.is_empty() {
Vec::new()
} else {
vec![(ptr, entries)]
};
DataSources { entries }
}
pub fn is_empty(&self) -> bool {
self.entries.iter().all(|(_, dss)| dss.is_empty())
}
fn append(&mut self, mut other: DataSources) {
self.entries.append(&mut other.entries);
}
}
/// Indicate to code that looks up entities from the in-memory batch whether
/// the entity in question will be written or removed at the block of the
/// lookup
#[derive(Debug, PartialEq)]
pub enum EntityOp<'a> {
/// There is a new version of the entity that will be written
Write {
key: &'a EntityKey,
entity: &'a Entity,
},
/// The entity has been removed
Remove { key: &'a EntityKey },
}
/// A write batch. This data structure encapsulates all the things that need
/// to be changed to persist the output of mappings up to a certain block.
#[derive(Debug)]
pub struct Batch {
/// The last block for which this batch contains changes
pub block_ptr: BlockPtr,
/// The timestamp for each block number we've seen as batches have been
/// appended to this one. This will have one entry for each block where
/// the subgraph performed a write. Entries are in ascending order of
/// block number
pub block_times: Vec<(BlockNumber, BlockTime)>,
/// The first block for which this batch contains changes
pub first_block: BlockNumber,
/// The firehose cursor corresponding to `block_ptr`
pub firehose_cursor: FirehoseCursor,
pub mods: RowGroups,
/// New data sources
pub data_sources: DataSources,
pub deterministic_errors: Vec<SubgraphError>,
pub offchain_to_remove: DataSources,
pub error: Option<StoreError>,
pub is_non_fatal_errors_active: bool,
/// Memoize the indirect weight of the batch. We need the `CacheWeight`
/// of the batch a lot in the write queue to determine if a batch should
/// be written. Recalculating it every time, which has to happen while
/// the writer holds a lock, conflicts with appending to the batch and
/// causes batches to be finished prematurely.
indirect_weight: usize,
}
impl Batch {
pub fn new(
block_ptr: BlockPtr,
block_time: BlockTime,
firehose_cursor: FirehoseCursor,
mut raw_mods: Vec<EntityModification>,
data_sources: Vec<StoredDynamicDataSource>,
deterministic_errors: Vec<SubgraphError>,
offchain_to_remove: Vec<StoredDynamicDataSource>,
is_non_fatal_errors_active: bool,
logger: Logger,
) -> Result<Self, StoreError> {
let block = block_ptr.number;
// Sort the modifications such that writes and clamps are
// consecutive. It's not needed for correctness but helps with some
// of the iterations, especially when we iterate with
// `clamps_by_block` so we get only one run for each block
raw_mods.sort_unstable_by_key(|emod| match emod {
EntityModification::Insert { .. } => 2,
EntityModification::Overwrite { .. } => 1,
EntityModification::Remove { .. } => 0,
});
let mut mods = RowGroups::new(logger);
for m in raw_mods {
mods.group_entry(&m.key().entity_type).push(m, block)?;
}
let data_sources = DataSources::new(block_ptr.cheap_clone(), data_sources);
let offchain_to_remove = DataSources::new(block_ptr.cheap_clone(), offchain_to_remove);
let first_block = block_ptr.number;
let block_times = vec![(block, block_time)];
let mut batch = Self {
block_ptr,
first_block,
block_times,
firehose_cursor,
mods,
data_sources,
deterministic_errors,
offchain_to_remove,
error: None,
is_non_fatal_errors_active,
indirect_weight: 0,
};
batch.weigh();
Ok(batch)
}
fn append_inner(&mut self, mut batch: Batch) -> Result<(), StoreError> {
if batch.block_ptr.number <= self.block_ptr.number {
return Err(internal_error!("Batches must go forward. Can't append a batch with block pointer {} to one with block pointer {}", batch.block_ptr, self.block_ptr));
}
self.block_ptr = batch.block_ptr;
self.block_times.append(&mut batch.block_times);
self.firehose_cursor = batch.firehose_cursor;
self.mods.append(batch.mods)?;
self.data_sources.append(batch.data_sources);
self.deterministic_errors
.append(&mut batch.deterministic_errors);
self.offchain_to_remove.append(batch.offchain_to_remove);
Ok(())
}
/// Append `batch` to `self` so that writing `self` afterwards has the
/// same effect as writing `self` first and then `batch` in separate
/// transactions.
///
/// When this method returns an `Err`, the batch is marked as not
/// healthy by setting `self.error` to `Some(_)` and must not be written
/// as it will be in an indeterminate state.
pub fn append(&mut self, batch: Batch) -> Result<(), StoreError> {
let res = self.append_inner(batch);
if let Err(e) = &res {
self.error = Some(e.clone());
}
self.weigh();
res
}
pub fn entity_count(&self) -> usize {
self.mods.entity_count()
}
/// Find out whether the latest operation for the entity with type
/// `entity_type` and `id` is going to write that entity, i.e., insert
/// or overwrite it, or if it is going to remove it. If no change will
/// be made to the entity, return `None`
pub fn last_op(&self, key: &EntityKey, block: BlockNumber) -> Option<EntityOp<'_>> {
self.mods.group(&key.entity_type)?.last_op(key, block)
}
pub fn effective_ops(
&self,
entity_type: &EntityType,
at: BlockNumber,
) -> impl Iterator<Item = EntityOp<'_>> {
self.mods
.group(entity_type)
.map(|group| group.effective_ops(at))
.into_iter()
.flatten()
}
pub fn new_data_sources(
&self,
at: BlockNumber,
) -> impl Iterator<Item = &StoredDynamicDataSource> {
self.data_sources
.entries
.iter()
.filter(move |(ptr, _)| ptr.number <= at)
.flat_map(|(_, ds)| ds)
.filter(|ds| {
!self
.offchain_to_remove
.entries
.iter()
.any(|(_, entries)| entries.contains(ds))
})
}
pub fn groups(&self) -> impl Iterator<Item = &RowGroup> {
self.mods.groups.iter()
}
fn weigh(&mut self) {
self.indirect_weight = self.mods.indirect_weight();
}
}
impl CacheWeight for Batch {
fn indirect_weight(&self) -> usize {
self.indirect_weight
}
}
pub struct WriteChunker<'a> {
group: &'a RowGroup,
chunk_size: usize,
position: usize,
}
impl<'a> WriteChunker<'a> {
fn new(group: &'a RowGroup, chunk_size: usize) -> Self {
Self {
group,
chunk_size,
position: 0,
}
}
}
impl<'a> Iterator for WriteChunker<'a> {
type Item = WriteChunk<'a>;
fn next(&mut self) -> Option<Self::Item> {
// Produce a chunk according to the current `self.position`
let res = if self.position < self.group.rows.len() {
Some(WriteChunk {
group: self.group,
chunk_size: self.chunk_size,
position: self.position,
})
} else {
None
};
// Advance `self.position` to the start of the next chunk
let mut count = 0;
while count < self.chunk_size && self.position < self.group.rows.len() {
if self.group.rows[self.position].is_write() {
count += 1;
}
self.position += 1;
}
res
}
}
#[derive(Debug)]
pub struct WriteChunk<'a> {
group: &'a RowGroup,
chunk_size: usize,
position: usize,
}
impl<'a> WriteChunk<'a> {
pub fn is_empty(&'a self) -> bool {
self.iter().next().is_none()
}
pub fn len(&self) -> usize {
(self.group.row_count() - self.position).min(self.chunk_size)
}
pub fn iter(&self) -> WriteChunkIter<'a> {
WriteChunkIter {
group: self.group,
chunk_size: self.chunk_size,
position: self.position,
count: 0,
}
}
/// Return a vector of `WriteChunk`s each containing a single write
pub fn as_single_writes(&self) -> Vec<Self> {
(0..self.len())
.map(|position| WriteChunk {
group: self.group,
chunk_size: 1,
position: self.position + position,