/
ReadYourWrites.actor.cpp
1918 lines (1592 loc) · 68.2 KB
/
ReadYourWrites.actor.cpp
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
/*
* ReadYourWrites.actor.cpp
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2018 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "flow/actorcompiler.h"
#include "ReadYourWrites.h"
#include "Atomic.h"
#include "DatabaseContext.h"
#include "StatusClient.h"
#include "MonitorLeader.h"
class RYWImpl {
public:
template<class Iter> static void dump( Iter it ) {
it.skip(allKeys.begin);
Arena arena;
while( true ) {
TraceEvent("RYWDump").detail("Begin", printable(it.beginKey().toStandaloneStringRef()))
.detail("End", printable(it.endKey().toStandaloneStringRef()))
.detail("Unknown", it.is_unknown_range())
.detail("Empty", it.is_empty_range())
.detail("KV", it.is_kv())
.detail("Key", printable(it.is_kv() ? it.kv(arena).key : StringRef()));
if( it.endKey() == allKeys.end )
break;
++it;
}
}
struct GetValueReq {
explicit GetValueReq( Key key ) : key(key) {}
Key key;
typedef Optional<Value> Result;
};
struct GetKeyReq {
explicit GetKeyReq( KeySelector key ) : key(key) {}
KeySelector key;
typedef Key Result;
};
template <bool Reverse>
struct GetRangeReq {
GetRangeReq( KeySelector begin, KeySelector end, GetRangeLimits limits ) : begin(begin), end(end), limits(limits) {}
KeySelector begin, end;
GetRangeLimits limits;
typedef Standalone<RangeResultRef> Result;
};
// read() Performs a read (get, getKey, getRange, etc), in the context of the given transaction. Snapshot or RYW reads are distingushed by the type Iter being SnapshotCache::iterator or RYWIterator.
// Fills in the snapshot cache as a side effect but does not affect conflict ranges.
// Some (indicated) overloads of read are required to update the given *it to point to the key that was read, so that the corresponding overload of addConflictRange() can make use of it.
ACTOR template<class Iter> static Future< Optional<Value> > read( ReadYourWritesTransaction *ryw, GetValueReq read, Iter* it ) {
// This overload is required to provide postcondition: it->extractWriteMapIterator().segmentContains(read.key)
it->skip(read.key);
state bool dependent = it->is_dependent();
if( it->is_kv() ) {
return it->kv(ryw->arena).value;
} else if( it->is_empty_range() ) {
return Optional<Value>();
} else {
Optional<Value> res = wait( ryw->tr.get( read.key, true ) );
KeyRef k( ryw->arena, read.key );
if( res.present() ) {
if( ryw->cache.insert( k, res.get() ) )
ryw->arena.dependsOn(res.get().arena());
if( !dependent )
return res;
} else {
ryw->cache.insert( k, Optional<ValueRef>() );
if( !dependent )
return Optional<Value>();
}
//There was a dependent write at the key, so we need to lookup the iterator again
it->skip(k);
ASSERT( it->is_kv() );
return it->kv(ryw->arena).value;
}
}
ACTOR template<class Iter> static Future< Key > read( ReadYourWritesTransaction* ryw, GetKeyReq read, Iter* it ) {
if( read.key.offset > 0 ) {
Standalone<RangeResultRef> result = wait( getRangeValue( ryw, read.key, firstGreaterOrEqual(ryw->getMaxReadKey()), GetRangeLimits(1), it ) );
if( result.readToBegin )
return allKeys.begin;
if( result.readThroughEnd || !result.size() )
return ryw->getMaxReadKey();
return result[0].key;
} else {
read.key.offset++;
Standalone<RangeResultRef> result = wait( getRangeValueBack( ryw, firstGreaterOrEqual(allKeys.begin), read.key, GetRangeLimits(1), it ) );
if( result.readThroughEnd )
return ryw->getMaxReadKey();
if( result.readToBegin || !result.size() )
return allKeys.begin;
return result[0].key;
}
};
template <class Iter> static Future< Standalone<RangeResultRef> > read( ReadYourWritesTransaction* ryw, GetRangeReq<false> read, Iter* it ) {
return getRangeValue( ryw, read.begin, read.end, read.limits, it );
};
template <class Iter> static Future< Standalone<RangeResultRef> > read( ReadYourWritesTransaction* ryw, GetRangeReq<true> read, Iter* it ) {
return getRangeValueBack( ryw, read.begin, read.end, read.limits, it );
};
// readThrough() performs a read in the RYW disabled case, passing it on relatively directly to the underlying transaction.
// Responsible for clipping results to the non-system keyspace when appropriate, since NativeAPI doesn't do that.
static Future<Optional<Value>> readThrough( ReadYourWritesTransaction *ryw, GetValueReq read, bool snapshot ) {
return ryw->tr.get( read.key, snapshot );
}
ACTOR static Future<Key> readThrough( ReadYourWritesTransaction *ryw, GetKeyReq read, bool snapshot ) {
Key key = wait( ryw->tr.getKey( read.key, snapshot ) );
if (ryw->getMaxReadKey() < key) return ryw->getMaxReadKey(); // Filter out results in the system keys if they are not accessible
return key;
}
ACTOR template <bool Reverse> static Future<Standalone<RangeResultRef>> readThrough( ReadYourWritesTransaction *ryw, GetRangeReq<Reverse> read, bool snapshot ) {
if(Reverse && read.end.offset > 1) {
// FIXME: Optimistically assume that this will not run into the system keys, and only reissue if the result actually does.
Key key = wait( ryw->tr.getKey(read.end, snapshot) );
if(key > ryw->getMaxReadKey())
read.end = firstGreaterOrEqual(ryw->getMaxReadKey());
else
read.end = KeySelector(firstGreaterOrEqual(key), key.arena());
}
Standalone<RangeResultRef> v = wait( ryw->tr.getRange(read.begin, read.end, read.limits, snapshot, Reverse) );
KeyRef maxKey = ryw->getMaxReadKey();
if(v.size() > 0) {
if(!Reverse && v[v.size()-1].key >= maxKey) {
state Standalone<RangeResultRef> _v = v;
int i = _v.size() - 2;
for(; i >= 0 && _v[i].key >= maxKey; --i) { }
return Standalone<RangeResultRef>(RangeResultRef( VectorRef<KeyValueRef>(&_v[0], i+1), false ), _v.arena());
}
}
return v;
}
// addConflictRange(ryw,read,result) is called after a serializable read and is responsible for adding the relevant conflict range
static void addConflictRange( ReadYourWritesTransaction* ryw, GetValueReq read, WriteMap::iterator& it, Optional<Value> result ) {
// it will already point to the right segment (see the calling code in read()), so we don't need to skip
// read.key will be copied into ryw->arena inside of updateConflictMap if it is being added
ryw->updateConflictMap(read.key, it);
}
static void addConflictRange( ReadYourWritesTransaction* ryw, GetKeyReq read, WriteMap::iterator& it, Key result ) {
KeyRangeRef readRange;
if( read.key.offset <= 0 )
readRange = KeyRangeRef( KeyRef( ryw->arena, result ), read.key.orEqual ? keyAfter( read.key.getKey(), ryw->arena ) : KeyRef( ryw->arena, read.key.getKey() ) );
else
readRange = KeyRangeRef( read.key.orEqual ? keyAfter( read.key.getKey(), ryw->arena ) : KeyRef( ryw->arena, read.key.getKey() ), keyAfter( result, ryw->arena ) );
it.skip( readRange.begin );
ryw->updateConflictMap(readRange, it);
}
static void addConflictRange( ReadYourWritesTransaction* ryw, GetRangeReq<false> read, WriteMap::iterator &it, Standalone<RangeResultRef> const& result ) {
KeyRef rangeBegin, rangeEnd;
bool endInArena = false;
if( read.begin.getKey() < read.end.getKey() ) {
rangeBegin = read.begin.getKey();
rangeEnd = read.end.offset > 0 && result.more ? read.begin.getKey() : read.end.getKey();
}
else {
rangeBegin = read.end.getKey();
rangeEnd = read.begin.getKey();
}
if( result.readToBegin && read.begin.offset <= 0 ) rangeBegin = allKeys.begin;
if( result.readThroughEnd && read.end.offset > 0 ) rangeEnd = ryw->getMaxReadKey();
if ( result.size() ) {
if( read.begin.offset <= 0 ) rangeBegin = std::min( rangeBegin, result[0].key );
if( rangeEnd <= result.end()[-1].key ) {
rangeEnd = keyAfter( result.end()[-1].key, ryw->arena );
endInArena = true;
}
}
KeyRangeRef readRange = KeyRangeRef( KeyRef( ryw->arena, rangeBegin ), endInArena ? rangeEnd : KeyRef( ryw->arena, rangeEnd ) );
it.skip( readRange.begin );
ryw->updateConflictMap(readRange, it);
}
static void addConflictRange( ReadYourWritesTransaction* ryw, GetRangeReq<true> read, WriteMap::iterator& it, Standalone<RangeResultRef> const& result ) {
KeyRef rangeBegin, rangeEnd;
bool endInArena = false;
if( read.begin.getKey() < read.end.getKey() ) {
rangeBegin = read.begin.offset <= 0 && result.more ? read.end.getKey() : read.begin.getKey();
rangeEnd = read.end.getKey();
}
else {
rangeBegin = read.end.getKey();
rangeEnd = read.begin.getKey();
}
if( result.readToBegin && read.begin.offset <= 0 ) rangeBegin = allKeys.begin;
if( result.readThroughEnd && read.end.offset > 0 ) rangeEnd = ryw->getMaxReadKey();
if ( result.size() ) {
rangeBegin = std::min( rangeBegin, result.end()[-1].key );
if( read.end.offset > 0 && rangeEnd <= result[0].key ) {
rangeEnd = keyAfter( result[0].key, ryw->arena );
endInArena = true;
}
}
KeyRangeRef readRange = KeyRangeRef( KeyRef( ryw->arena, rangeBegin ), endInArena ? rangeEnd : KeyRef( ryw->arena, rangeEnd ) );
it.skip( readRange.begin );
ryw->updateConflictMap(readRange, it);
}
ACTOR template <class Req> static Future<typename Req::Result> readWithConflictRangeThrough( ReadYourWritesTransaction* ryw, Req req, bool snapshot ) {
choose {
when (typename Req::Result result = wait( readThrough( ryw, req, snapshot ) )) {
return result;
}
when (Void _ = wait(ryw->resetPromise.getFuture())) { throw internal_error(); }
}
}
ACTOR template <class Req> static Future<typename Req::Result> readWithConflictRangeSnapshot( ReadYourWritesTransaction* ryw, Req req ) {
state SnapshotCache::iterator it(&ryw->cache, &ryw->writes);
choose {
when (typename Req::Result result = wait( read( ryw, req, &it ) )) {
return result;
}
when (Void _ = wait(ryw->resetPromise.getFuture())) { throw internal_error(); }
}
}
ACTOR template <class Req> static Future<typename Req::Result> readWithConflictRangeRYW( ReadYourWritesTransaction* ryw, Req req, bool snapshot ) {
state RYWIterator it( &ryw->cache, &ryw->writes );
choose {
when (typename Req::Result result = wait( read( ryw, req, &it ) )) {
// Some overloads of addConflictRange() require it to point to the "right" key and others don't. The corresponding overloads of read() have to provide that guarantee!
if(!snapshot)
addConflictRange( ryw, req, it.extractWriteMapIterator(), result );
return result;
}
when (Void _ = wait(ryw->resetPromise.getFuture())) { throw internal_error(); }
}
}
template <class Req> static inline Future<typename Req::Result> readWithConflictRange( ReadYourWritesTransaction* ryw, Req const& req, bool snapshot ) {
if (ryw->options.readYourWritesDisabled) {
return readWithConflictRangeThrough(ryw, req, snapshot);
} else if (snapshot && ryw->options.snapshotRywEnabled <= 0) {
return readWithConflictRangeSnapshot(ryw, req);
}
return readWithConflictRangeRYW(ryw, req, snapshot);
}
template<class Iter> static void resolveKeySelectorFromCache( KeySelector& key, Iter& it, KeyRef const& maxKey, bool* readToBegin, bool* readThroughEnd, int* actualOffset ) {
// If the key indicated by `key` can be determined without reading unknown data from the snapshot, then it.kv().key is the resolved key.
// If the indicated key is determined to be "off the beginning or end" of the database, it points to the first or last segment in the DB,
// and key is an equivalent key selector relative to the beginning or end of the database.
// Otherwise it points to an unknown segment, and key is an equivalent key selector whose base key is in or adjoining the segment.
key.removeOrEqual(key.arena());
bool alreadyExhausted = key.offset == 1;
it.skip( key.getKey() ); // TODO: or precondition?
if ( key.offset <= 0 && it.beginKey() == key.getKey() && key.getKey() != allKeys.begin )
--it;
ExtStringRef keykey = key.getKey();
bool keyNeedsCopy = false;
// Invariant: it.beginKey() <= keykey && keykey <= it.endKey() && (key.isBackward() ? it.beginKey() != keykey : it.endKey() != keykey)
// Maintaining this invariant, we transform the key selector toward firstGreaterOrEqual form until we reach an unknown range or the result
while (key.offset > 1 && !it.is_unreadable() && !it.is_unknown_range() && it.endKey() < maxKey ) {
if (it.is_kv())
--key.offset;
++it;
keykey = it.beginKey();
keyNeedsCopy = true;
}
while (key.offset < 1 && !it.is_unreadable() && !it.is_unknown_range() && it.beginKey() != allKeys.begin) {
if (it.is_kv()) {
++key.offset;
if (key.offset == 1) {
keykey = it.beginKey();
keyNeedsCopy = true;
break;
}
}
--it;
keykey = it.endKey();
keyNeedsCopy = true;
}
if(!alreadyExhausted) {
*actualOffset = key.offset;
}
if (!it.is_unreadable() && !it.is_unknown_range() && key.offset < 1) {
*readToBegin = true;
key.setKey(allKeys.begin);
key.offset = 1;
return;
}
if (!it.is_unreadable() && !it.is_unknown_range() && key.offset > 1) {
*readThroughEnd = true;
key.setKey(maxKey); // maxKey is a KeyRef, but points to a LiteralStringRef. TODO: how can we ASSERT this?
key.offset = 1;
return;
}
while (!it.is_unreadable() && it.is_empty_range() && it.endKey() < maxKey) {
++it;
keykey = it.beginKey();
keyNeedsCopy = true;
}
if(keyNeedsCopy) {
key.setKey(keykey.toArena(key.arena()));
}
}
static KeyRangeRef getKnownKeyRange( RangeResultRef data, KeySelector begin, KeySelector end, Arena& arena ) {
StringRef beginKey = begin.offset<=1 ? begin.getKey() : allKeys.end;
ExtStringRef endKey = !data.more && end.offset>=1 ? end.getKey() : allKeys.begin;
if (data.readToBegin) beginKey = allKeys.begin;
if (data.readThroughEnd) endKey = allKeys.end;
if( data.size() ) {
beginKey = std::min( beginKey, data[0].key );
if( data.readThrough.present() ) {
endKey = std::max<ExtStringRef>( endKey, data.readThrough.get() );
}
else {
endKey = !data.more && data.end()[-1].key < endKey ? endKey : ExtStringRef( data.end()[-1].key, 1 );
}
}
if (beginKey >= endKey) return KeyRangeRef();
return KeyRangeRef( StringRef(arena, beginKey), endKey.toArena(arena));
}
// Pre: it points to an unknown range
// Increments it to point to the unknown range just before the next nontrivial known range (skips over trivial known ranges), but not more than iterationLimit ranges away
template<class Iter> static int skipUncached( Iter& it, Iter const& end, int iterationLimit ) {
ExtStringRef b = it.beginKey();
ExtStringRef e = it.endKey();
int singleEmpty = 0;
ASSERT( !it.is_unreadable() && it.is_unknown_range() );
// b is the beginning of the most recent contiguous *empty* range
// e is it.endKey()
while( it != end && --iterationLimit>=0 ) {
if (it.is_unreadable() || it.is_empty_range()) {
if (it.is_unreadable() || !e.isKeyAfter(b)) { //Assumes no degenerate ranges
while (it.is_unreadable() || !it.is_unknown_range())
--it;
return singleEmpty;
}
singleEmpty++;
} else
b = e;
++it;
e = it.endKey();
}
while (it.is_unreadable() || !it.is_unknown_range())
--it;
return singleEmpty;
}
// Pre: it points to an unknown range
// Returns the number of following empty single-key known ranges between it and the next nontrivial known range, but no more than maxClears
// Leaves `it` in an indeterminate state
template<class Iter> static int countUncached( Iter&& it, KeyRef maxKey, int maxClears ) {
if (maxClears<=0) return 0;
ExtStringRef b = it.beginKey();
ExtStringRef e = it.endKey();
int singleEmpty = 0;
while( e < maxKey ) {
if (it.is_unreadable() || it.is_empty_range()) {
if (it.is_unreadable() || !e.isKeyAfter(b)) { //Assumes no degenerate ranges
return singleEmpty;
}
singleEmpty++;
if( singleEmpty >= maxClears )
return maxClears;
} else
b = e;
++it;
e = it.endKey();
}
return singleEmpty;
}
static void setRequestLimits(GetRangeLimits &requestLimit, int64_t additionalRows, int offset, int requestCount) {
requestLimit.minRows = (int)std::min(std::max(1 + additionalRows, (int64_t)offset), (int64_t)std::numeric_limits<int>::max());
if(requestLimit.hasRowLimit()) {
requestLimit.rows = (int)std::min(std::max(std::max(1,requestLimit.rows) + additionalRows, (int64_t)offset), (int64_t)std::numeric_limits<int>::max());
}
// Calculating request byte limit
if(requestLimit.bytes==0) {
requestLimit.bytes = CLIENT_KNOBS->BYTE_LIMIT_UNLIMITED;
if(!requestLimit.hasRowLimit()) {
requestLimit.rows = (int)std::min(std::max(std::max(1,requestLimit.rows) + additionalRows, (int64_t)offset), (int64_t)std::numeric_limits<int>::max());
}
}
else if(requestLimit.hasByteLimit()) {
requestLimit.bytes = std::min(int64_t(requestLimit.bytes)<<std::min(requestCount, 20), (int64_t)CLIENT_KNOBS->REPLY_BYTE_LIMIT);
}
}
//TODO: read to begin, read through end flags for result
ACTOR template<class Iter> static Future< Standalone<RangeResultRef> > getRangeValue( ReadYourWritesTransaction *ryw, KeySelector begin, KeySelector end, GetRangeLimits limits, Iter* pit ) {
state Iter& it(*pit);
state Iter itEnd(*pit);
state Standalone<RangeResultRef> result;
state int64_t additionalRows = 0;
state int itemsPastEnd = 0;
state int requestCount = 0;
state bool readToBegin = false;
state bool readThroughEnd = false;
state int actualBeginOffset = begin.offset;
state int actualEndOffset = end.offset;
//state UID randomID = g_nondeterministic_random->randomUniqueID();
resolveKeySelectorFromCache( begin, it, ryw->getMaxReadKey(), &readToBegin, &readThroughEnd, &actualBeginOffset );
resolveKeySelectorFromCache( end, itEnd, ryw->getMaxReadKey(), &readToBegin, &readThroughEnd, &actualEndOffset );
if( actualBeginOffset >= actualEndOffset && begin.getKey() >= end.getKey() ) {
return RangeResultRef(false, false);
}
else if( ( begin.isFirstGreaterOrEqual() && begin.getKey() == ryw->getMaxReadKey() )
|| ( end.isFirstGreaterOrEqual() && end.getKey() == allKeys.begin ) )
{
return RangeResultRef(readToBegin, readThroughEnd);
}
if( !end.isFirstGreaterOrEqual() && begin.getKey() > end.getKey() ) {
Key resolvedEnd = wait( read( ryw, GetKeyReq(end), pit ) );
if( resolvedEnd == allKeys.begin )
readToBegin = true;
if( resolvedEnd == ryw->getMaxReadKey() )
readThroughEnd = true;
if( begin.getKey() >= resolvedEnd && !begin.isBackward() ) {
return RangeResultRef(false, false);
}
else if( resolvedEnd == allKeys.begin ) {
return RangeResultRef(readToBegin, readThroughEnd);
}
resolveKeySelectorFromCache( begin, it, ryw->getMaxReadKey(), &readToBegin, &readThroughEnd, &actualBeginOffset );
resolveKeySelectorFromCache( end, itEnd, ryw->getMaxReadKey(), &readToBegin, &readThroughEnd, &actualEndOffset );
}
//TraceEvent("RYWSelectorsStartForward", randomID).detail("ByteLimit", limits.bytes).detail("RowLimit", limits.rows);
loop {
/*TraceEvent("RYWSelectors", randomID).detail("begin", begin.toString())
.detail("end", end.toString())
.detail("reached", limits.isReached())
.detail("itemsPastEnd", itemsPastEnd)
.detail("endOffset", -end.offset)
.detail("itBegin", printable(it.beginKey().toStandaloneStringRef()))
.detail("itEnd", printable(itEnd.beginKey().toStandaloneStringRef()))
.detail("unknown", it.is_unknown_range())
.detail("requests", requestCount);*/
if( !result.size() && actualBeginOffset >= actualEndOffset && begin.getKey() >= end.getKey() ) {
return RangeResultRef(false, false);
}
if( end.offset <= 1 && end.getKey() == allKeys.begin ) {
return RangeResultRef(readToBegin, readThroughEnd);
}
if( ( begin.offset >= end.offset && begin.getKey() >= end.getKey() ) ||
( begin.offset >= 1 && begin.getKey() >= ryw->getMaxReadKey() ) ) {
if( end.isFirstGreaterOrEqual() ) break;
if( !result.size() ) break;
Key resolvedEnd = wait( read( ryw, GetKeyReq(end), pit ) ); //do not worry about iterator invalidation, because we are breaking for the loop
if( resolvedEnd == allKeys.begin )
readToBegin = true;
if( resolvedEnd == ryw->getMaxReadKey() )
readThroughEnd = true;
end = firstGreaterOrEqual( resolvedEnd );
break;
}
if( !it.is_unreadable() && !it.is_unknown_range() && it.beginKey() > itEnd.beginKey() ) {
if( end.isFirstGreaterOrEqual() ) break;
return RangeResultRef(readToBegin, readThroughEnd);
}
if( limits.isReached() && itemsPastEnd >= 1-end.offset ) break;
if (it == itEnd && ((!it.is_unreadable() && !it.is_unknown_range()) || (begin.offset > 0 && end.isFirstGreaterOrEqual() && end.getKey() == it.beginKey()))) break;
if (it.is_unknown_range()) {
if( limits.hasByteLimit() && result.size() && itemsPastEnd >= 1-end.offset ) {
result.more = true;
break;
}
Iter ucEnd(it);
int singleClears = 0;
int clearLimit = requestCount ? 1 << std::min(requestCount, 20) : 0;
if( it.beginKey() < itEnd.beginKey() )
singleClears = std::min(skipUncached(ucEnd, itEnd, BUGGIFY ? 0 : clearLimit + 100), clearLimit);
state KeySelector read_end;
if ( ucEnd!=itEnd ) {
Key k = ucEnd.endKey().toStandaloneStringRef();
read_end = KeySelector(firstGreaterOrEqual(k), k.arena());
if( end.offset < 1 ) additionalRows += 1 - end.offset; // extra for items past end
} else if( end.offset < 1 ) {
read_end = KeySelector(firstGreaterOrEqual(end.getKey()), end.arena());
additionalRows += 1 - end.offset;
} else {
read_end = end;
if( end.offset > 1 ) {
singleClears += countUncached( std::move(ucEnd), ryw->getMaxReadKey(), clearLimit-singleClears);
read_end.offset += singleClears;
}
}
additionalRows += singleClears;
state KeySelector read_begin;
if (begin.isFirstGreaterOrEqual()) {
Key k = it.beginKey() > begin.getKey() ? it.beginKey().toStandaloneStringRef() : Key(begin.getKey(), begin.arena());
begin = KeySelector(firstGreaterOrEqual(k), k.arena());
read_begin = begin;
} else if( begin.offset > 1 ) {
read_begin = KeySelector(firstGreaterOrEqual(begin.getKey()), begin.arena());
additionalRows += begin.offset - 1;
} else {
read_begin = begin;
ucEnd = it;
singleClears = countUncachedBack(std::move(ucEnd), clearLimit);
read_begin.offset -= singleClears;
additionalRows += singleClears;
}
if(read_end.getKey() < read_begin.getKey()) {
read_end.setKey(read_begin.getKey());
read_end.arena().dependsOn(read_begin.arena());
}
state GetRangeLimits requestLimit = limits;
setRequestLimits(requestLimit, additionalRows, 2-read_begin.offset, requestCount);
requestCount++;
ASSERT( !requestLimit.hasRowLimit() || requestLimit.rows > 0 );
ASSERT( requestLimit.hasRowLimit() || requestLimit.hasByteLimit() );
//TraceEvent("RYWIssuing", randomID).detail("begin", read_begin.toString()).detail("end", read_end.toString()).detail("bytes", requestLimit.bytes).detail("rows", requestLimit.rows).detail("limits", limits.bytes).detail("reached", limits.isReached()).detail("requestCount", requestCount).detail("singleClears", singleClears).detail("ucEnd", printable(ucEnd.beginKey().toStandaloneStringRef())).detail("minRows", requestLimit.minRows);
additionalRows = 0;
Standalone<RangeResultRef> snapshot_read = wait( ryw->tr.getRange( read_begin, read_end, requestLimit, true, false ) );
KeyRangeRef range = getKnownKeyRange( snapshot_read, read_begin, read_end, ryw->arena );
//TraceEvent("RYWCacheInsert", randomID).detail("Range", printable(range)).detail("expectedSize", snapshot_read.expectedSize()).detail("rows", snapshot_read.size()).detail("results", printable(snapshot_read)).detail("more", snapshot_read.more).detail("readToBegin", snapshot_read.readToBegin).detail("readThroughEnd", snapshot_read.readThroughEnd).detail("readThrough", printable(snapshot_read.readThrough));
if( ryw->cache.insert( range, snapshot_read ) )
ryw->arena.dependsOn(snapshot_read.arena());
// TODO: Is there a more efficient way to deal with invalidation?
resolveKeySelectorFromCache( begin, it, ryw->getMaxReadKey(), &readToBegin, &readThroughEnd, &actualBeginOffset );
resolveKeySelectorFromCache( end, itEnd, ryw->getMaxReadKey(), &readToBegin, &readThroughEnd, &actualEndOffset );
} else if (it.is_kv()) {
KeyValueRef const* start = &it.kv(ryw->arena);
it.skipContiguous( end.isFirstGreaterOrEqual() ? end.getKey() : ryw->getMaxReadKey() ); //not technically correct since this would add end.getKey(), but that is protected above
int maxCount = &it.kv(ryw->arena) - start + 1;
int count = 0;
for(; count < maxCount && !limits.isReached(); count++ ) {
limits.decrement(start[count]);
}
itemsPastEnd += maxCount - count;
//TraceEvent("RYWaddKV", randomID).detail("key", printable(it.beginKey().toStandaloneStringRef())).detail("count", count).detail("maxCount", maxCount).detail("itemsPastEnd", itemsPastEnd);
if( count ) result.append( result.arena(), start, count );
++it;
} else
++it;
}
result.more = result.more || limits.isReached();
if( end.isFirstGreaterOrEqual() ) {
int keepItems = std::lower_bound( result.begin(), result.end(), end.getKey(), KeyValueRef::OrderByKey() ) - result.begin();
if( keepItems < result.size() )
result.more = false;
result.resize( result.arena(), keepItems );
}
result.readToBegin = readToBegin;
result.readThroughEnd = !result.more && readThroughEnd;
result.arena().dependsOn( ryw->arena );
return result;
}
static KeyRangeRef getKnownKeyRangeBack( RangeResultRef data, KeySelector begin, KeySelector end, Arena& arena ) {
StringRef beginKey = !data.more && begin.offset<=1 ? begin.getKey() : allKeys.end;
ExtStringRef endKey = end.offset>=1 ? end.getKey() : allKeys.begin;
if (data.readToBegin) beginKey = allKeys.begin;
if (data.readThroughEnd) endKey = allKeys.end;
if( data.size() ) {
if( data.readThrough.present() ) {
beginKey = std::min( data.readThrough.get(), beginKey );
}
else {
beginKey = !data.more && data.end()[-1].key > beginKey ? beginKey : data.end()[-1].key;
}
endKey = data[0].key < endKey ? endKey : ExtStringRef( data[0].key, 1 );
}
if (beginKey >= endKey) return KeyRangeRef();
return KeyRangeRef( StringRef(arena, beginKey), endKey.toArena(arena));
}
// Pre: it points to an unknown range
// Decrements it to point to the unknown range just before the last nontrivial known range (skips over trivial known ranges), but not more than iterationLimit ranges away
// Returns the number of single-key empty ranges skipped
template<class Iter> static int skipUncachedBack( Iter& it, Iter const& end, int iterationLimit ) {
ExtStringRef b = it.beginKey();
ExtStringRef e = it.endKey();
int singleEmpty = 0;
ASSERT(!it.is_unreadable() && it.is_unknown_range());
// b == it.beginKey()
// e is the end of the contiguous empty range containing it
while( it != end && --iterationLimit>=0) {
if (it.is_unreadable() || it.is_empty_range()) {
if (it.is_unreadable() || !e.isKeyAfter(b)) { //Assumes no degenerate ranges
while (it.is_unreadable() || !it.is_unknown_range())
++it;
return singleEmpty;
}
singleEmpty++;
} else
e = b;
--it;
b = it.beginKey();
}
while (it.is_unreadable() || !it.is_unknown_range())
++it;
return singleEmpty;
}
// Pre: it points to an unknown range
// Returns the number of preceding empty single-key known ranges between it and the previous nontrivial known range, but no more than maxClears
// Leaves it in an indeterminate state
template<class Iter> static int countUncachedBack( Iter&& it, int maxClears ) {
if (maxClears <= 0) return 0;
ExtStringRef b = it.beginKey();
ExtStringRef e = it.endKey();
int singleEmpty = 0;
while( b > allKeys.begin ) {
if (it.is_unreadable() || it.is_empty_range()) {
if (it.is_unreadable() || !e.isKeyAfter(b)) { //Assumes no degenerate ranges
return singleEmpty;
}
singleEmpty++;
if( singleEmpty >= maxClears )
return maxClears;
} else
e = b;
--it;
b = it.beginKey();
}
return singleEmpty;
}
ACTOR template<class Iter> static Future< Standalone<RangeResultRef> > getRangeValueBack( ReadYourWritesTransaction *ryw, KeySelector begin, KeySelector end, GetRangeLimits limits, Iter* pit ) {
state Iter& it(*pit);
state Iter itEnd(*pit);
state Standalone<RangeResultRef> result;
state int64_t additionalRows = 0;
state int itemsPastBegin = 0;
state int requestCount = 0;
state bool readToBegin = false;
state bool readThroughEnd = false;
state int actualBeginOffset = begin.offset;
state int actualEndOffset = end.offset;
//state UID randomID = g_nondeterministic_random->randomUniqueID();
resolveKeySelectorFromCache( end, it, ryw->getMaxReadKey(), &readToBegin, &readThroughEnd, &actualEndOffset );
resolveKeySelectorFromCache( begin, itEnd, ryw->getMaxReadKey(), &readToBegin, &readThroughEnd, &actualBeginOffset );
if( actualBeginOffset >= actualEndOffset && begin.getKey() >= end.getKey() ) {
return RangeResultRef(false, false);
}
else if( ( begin.isFirstGreaterOrEqual() && begin.getKey() == ryw->getMaxReadKey() )
|| ( end.isFirstGreaterOrEqual() && end.getKey() == allKeys.begin ) )
{
return RangeResultRef(readToBegin, readThroughEnd);
}
if( !begin.isFirstGreaterOrEqual() && begin.getKey() > end.getKey() ) {
Key resolvedBegin = wait( read( ryw, GetKeyReq(begin), pit ) );
if( resolvedBegin == allKeys.begin )
readToBegin = true;
if( resolvedBegin == ryw->getMaxReadKey() )
readThroughEnd = true;
if( resolvedBegin >= end.getKey() && end.offset <= 1 ) {
return RangeResultRef(false, false);
}
else if( resolvedBegin == ryw->getMaxReadKey() ) {
return RangeResultRef(readToBegin, readThroughEnd);
}
resolveKeySelectorFromCache( end, it, ryw->getMaxReadKey(), &readToBegin, &readThroughEnd, &actualEndOffset );
resolveKeySelectorFromCache( begin, itEnd, ryw->getMaxReadKey(), &readToBegin, &readThroughEnd, &actualBeginOffset );
}
//TraceEvent("RYWSelectorsStartReverse", randomID).detail("byteLimit", limits.bytes).detail("rowLimit", limits.rows);
loop {
/*TraceEvent("RYWSelectors", randomID).detail("begin", begin.toString())
.detail("end", end.toString())
.detail("reached", limits.isReached())
.detail("itemsPastBegin", itemsPastBegin)
.detail("endOffset", end.offset)
.detail("itBegin", printable(it.beginKey().toStandaloneStringRef()))
.detail("itEnd", printable(itEnd.beginKey().toStandaloneStringRef()))
.detail("unknown", it.is_unknown_range())
.detail("kv", it.is_kv())
.detail("requests", requestCount);*/
if(!result.size() && actualBeginOffset >= actualEndOffset && begin.getKey() >= end.getKey()) {
return RangeResultRef(false, false);
}
if( !begin.isBackward() && begin.getKey() >= ryw->getMaxReadKey() ) {
return RangeResultRef(readToBegin, readThroughEnd);
}
if( ( begin.offset >= end.offset && begin.getKey() >= end.getKey() ) ||
( end.offset <= 1 && end.getKey() == allKeys.begin ) ) {
if( begin.isFirstGreaterOrEqual() ) break;
if( !result.size() ) break;
Key resolvedBegin = wait( read( ryw, GetKeyReq(begin), pit ) ); //do not worry about iterator invalidation, because we are breaking for the loop
if( resolvedBegin == allKeys.begin )
readToBegin = true;
if( resolvedBegin == ryw->getMaxReadKey() )
readThroughEnd = true;
begin = firstGreaterOrEqual( resolvedBegin );
break;
}
if (itemsPastBegin >= begin.offset - 1 && !it.is_unreadable() && !it.is_unknown_range() && it.beginKey() < itEnd.beginKey()) {
if( begin.isFirstGreaterOrEqual() ) break;
return RangeResultRef(readToBegin, readThroughEnd);
}
if( limits.isReached() && itemsPastBegin >= begin.offset-1 ) break;
if( end.isFirstGreaterOrEqual() && end.getKey() == it.beginKey() ) {
if( itemsPastBegin >= begin.offset-1 && it == itEnd) break;
--it;
}
if (it.is_unknown_range()) {
if( limits.hasByteLimit() && result.size() && itemsPastBegin >= begin.offset-1 ) {
result.more = true;
break;
}
Iter ucEnd(it);
int singleClears = 0;
int clearLimit = requestCount ? 1 << std::min(requestCount, 20) : 0;
if( it.beginKey() > itEnd.beginKey() )
singleClears = std::min(skipUncachedBack(ucEnd, itEnd, BUGGIFY ? 0 : clearLimit+100), clearLimit);
state KeySelector read_begin;
if ( ucEnd!=itEnd ) {
Key k = ucEnd.beginKey().toStandaloneStringRef();
read_begin = KeySelector(firstGreaterOrEqual(k), k.arena());
if( begin.offset > 1 ) additionalRows += begin.offset - 1; // extra for items past end
} else if( begin.offset > 1 ) {
read_begin = KeySelector(firstGreaterOrEqual( begin.getKey() ), begin.arena());
additionalRows += begin.offset - 1;
} else {
read_begin = begin;
if( begin.offset < 1 ) {
singleClears += countUncachedBack(std::move(ucEnd), clearLimit-singleClears);
read_begin.offset -= singleClears;
}
}
additionalRows += singleClears;
state KeySelector read_end;
if (end.isFirstGreaterOrEqual()) {
Key k = it.endKey() < end.getKey() ? it.endKey().toStandaloneStringRef() : end.getKey();
end = KeySelector(firstGreaterOrEqual(k), k.arena());
read_end = end;
} else if (end.offset < 1) {
read_end = KeySelector(firstGreaterOrEqual(end.getKey()), end.arena());
additionalRows += 1 - end.offset;
} else {
read_end = end;
ucEnd = it;
singleClears = countUncached(std::move(ucEnd), ryw->getMaxReadKey(), clearLimit);
read_end.offset += singleClears;
additionalRows += singleClears;
}
if(read_begin.getKey() > read_end.getKey()) {
read_begin.setKey(read_end.getKey());
read_begin.arena().dependsOn(read_end.arena());
}
state GetRangeLimits requestLimit = limits;
setRequestLimits(requestLimit, additionalRows, read_end.offset, requestCount);
requestCount++;
ASSERT( !requestLimit.hasRowLimit() || requestLimit.rows > 0 );
ASSERT( requestLimit.hasRowLimit() || requestLimit.hasByteLimit() );
//TraceEvent("RYWIssuing", randomID).detail("begin", read_begin.toString()).detail("end", read_end.toString()).detail("bytes", requestLimit.bytes).detail("rows", requestLimit.rows).detail("limits", limits.bytes).detail("reached", limits.isReached()).detail("requestCount", requestCount).detail("singleClears", singleClears).detail("ucEnd", printable(ucEnd.beginKey().toStandaloneStringRef())).detail("minRows", requestLimit.minRows);
additionalRows = 0;
Standalone<RangeResultRef> snapshot_read = wait( ryw->tr.getRange( read_begin, read_end, requestLimit, true, true ) );
KeyRangeRef range = getKnownKeyRangeBack( snapshot_read, read_begin, read_end, ryw->arena );
//TraceEvent("RYWCacheInsert", randomID).detail("Range", printable(range)).detail("expectedSize", snapshot_read.expectedSize()).detail("rows", snapshot_read.size()).detail("results", printable(snapshot_read)).detail("more", snapshot_read.more).detail("readToBegin", snapshot_read.readToBegin).detail("readThroughEnd", snapshot_read.readThroughEnd).detail("readThrough", printable(snapshot_read.readThrough));
RangeResultRef reversed;
reversed.resize(ryw->arena, snapshot_read.size());
for( int i = 0; i < snapshot_read.size(); i++ ) {
reversed[snapshot_read.size()-i-1] = snapshot_read[i];
}
if( ryw->cache.insert( range, reversed ) )
ryw->arena.dependsOn(snapshot_read.arena());
// TODO: Is there a more efficient way to deal with invalidation?
resolveKeySelectorFromCache( end, it, ryw->getMaxReadKey(), &readToBegin, &readThroughEnd, &actualEndOffset );
resolveKeySelectorFromCache( begin, itEnd, ryw->getMaxReadKey(), &readToBegin, &readThroughEnd, &actualBeginOffset );
} else {
if (it.is_kv()) {
KeyValueRef const* end = &it.kv(ryw->arena);
it.skipContiguousBack( begin.isFirstGreaterOrEqual() ? begin.getKey() : allKeys.begin );
KeyValueRef const* start = &it.kv(ryw->arena);
int maxCount = end - start + 1;
int count = 0;
for(; count < maxCount && !limits.isReached(); count++ ) {
limits.decrement(start[maxCount-count-1]);
}
itemsPastBegin += maxCount - count;
//TraceEvent("RYWaddKV", randomID).detail("key", printable(it.beginKey().toStandaloneStringRef())).detail("count", count).detail("maxCount", maxCount).detail("itemsPastBegin", itemsPastBegin);
if( count ) {
int size = result.size();
result.resize(result.arena(),size+count);
for( int i = 0; i < count; i++ ) {
result[size + i] = start[maxCount-i-1];
}
}
}
if (it == itEnd) break;
--it;
}
}
result.more = result.more || limits.isReached();
if( begin.isFirstGreaterOrEqual() ) {
int keepItems = result.rend() - std::lower_bound( result.rbegin(), result.rend(), begin.getKey(), KeyValueRef::OrderByKey());
if( keepItems < result.size() )
result.more = false;
result.resize( result.arena(), keepItems );
}
result.readToBegin = !result.more && readToBegin;
result.readThroughEnd = readThroughEnd;
result.arena().dependsOn( ryw->arena );
return result;
}
static void triggerWatches(ReadYourWritesTransaction *ryw, KeyRangeRef range, Optional<ValueRef> val, bool valueKnown = true) {
for(auto it = ryw->watchMap.lower_bound(range.begin); it != ryw->watchMap.end() && it->key < range.end; ) {
auto itCopy = it;
++it;
ASSERT( itCopy->value.size() );
TEST( itCopy->value.size() > 1 ); //Multiple watches on the same key triggered by RYOW
for( int i = 0; i < itCopy->value.size(); i++ ) {
if(itCopy->value[i]->onChangeTrigger.isSet()) {
if( i < itCopy->value.size() - 1 )
std::swap(itCopy->value[i--], itCopy->value.back());
itCopy->value.pop_back();
} else if( !valueKnown ||
(itCopy->value[i]->setPresent && (itCopy->value[i]->setValue.present() != val.present() || (val.present() && itCopy->value[i]->setValue.get() != val.get()))) ||
(itCopy->value[i]->valuePresent && (itCopy->value[i]->value.present() != val.present() || (val.present() && itCopy->value[i]->value.get() != val.get()))) ) {
itCopy->value[i]->onChangeTrigger.send(Void());
if( i < itCopy->value.size() - 1 )
std::swap(itCopy->value[i--], itCopy->value.back());
itCopy->value.pop_back();
} else {
itCopy->value[i]->setPresent = true;
itCopy->value[i]->setValue = val.cast_to<Value>();
}
}
if( itCopy->value.size() == 0 )
ryw->watchMap.erase(itCopy);
}
}
static void triggerWatches(ReadYourWritesTransaction *ryw, KeyRef key, Optional<ValueRef> val, bool valueKnown = true) {
triggerWatches(ryw, singleKeyRange(key), val, valueKnown);
}
ACTOR static Future<Void> watch( ReadYourWritesTransaction *ryw, Key key ) {
state Future<Optional<Value>> val;
state Future<Void> watchFuture;
state Reference<Watch> watch(new Watch(key));
state Promise<Void> done;
ryw->reading.add( done.getFuture() );
if(!ryw->options.readYourWritesDisabled) {
ryw->watchMap[key].push_back(watch);
val = readWithConflictRange( ryw, GetValueReq(key), false );
}
else
val = ryw->tr.get(key);
try {
Void _ = wait(ryw->resetPromise.getFuture() || success(val) || watch->onChangeTrigger.getFuture());
} catch( Error &e ) {
done.send(Void());
throw;
}
if( watch->onChangeTrigger.getFuture().isReady() ) {
done.send(Void());
if( watch->onChangeTrigger.getFuture().isError() )
throw watch->onChangeTrigger.getFuture().getError();
return Void();
}
watch->valuePresent = true;
watch->value = val.get();
if( watch->setPresent && ( watch->setValue.present() != watch->value.present() || (watch->value.present() && watch->setValue.get() != watch->value.get()) ) ) {
watch->onChangeTrigger.send(Void());
done.send(Void());
return Void();
}