-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
data.go
1632 lines (1474 loc) · 51.4 KB
/
data.go
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
// Copyright 2014 The Cockroach 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.
package roachpb
import (
"bytes"
"context"
"encoding/binary"
"encoding/hex"
"fmt"
"hash"
"hash/crc32"
"math"
"math/rand"
"sort"
"strconv"
"sync"
"time"
"unicode"
"github.com/pkg/errors"
"github.com/cockroachdb/apd"
"github.com/cockroachdb/cockroach/pkg/storage/engine/enginepb"
"github.com/cockroachdb/cockroach/pkg/util/duration"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/interval"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
)
var (
// RKeyMin is a minimum key value which sorts before all other keys.
RKeyMin = RKey("")
// KeyMin is a minimum key value which sorts before all other keys.
KeyMin = Key(RKeyMin)
// RKeyMax is a maximum key value which sorts after all other keys.
RKeyMax = RKey{0xff, 0xff}
// KeyMax is a maximum key value which sorts after all other keys.
KeyMax = Key(RKeyMax)
// PrettyPrintKey prints a key in human readable format. It's
// implemented in package git.com/cockroachdb/cockroach/keys to avoid
// package circle import.
// valDirs correspond to the encoding direction of each encoded value
// in the key (if known). If left unspecified, the default encoding
// direction for each value type is used (see
// encoding.go:prettyPrintFirstValue).
PrettyPrintKey func(valDirs []encoding.Direction, key Key) string
// PrettyPrintRange prints a key range in human readable format. It's
// implemented in package git.com/cockroachdb/cockroach/keys to avoid
// package circle import.
PrettyPrintRange func(start, end Key, maxChars int) string
)
// RKey denotes a Key whose local addressing has been accounted for.
// A key can be transformed to an RKey by keys.Addr().
type RKey Key
// AsRawKey returns the RKey as a Key. This is to be used only in select
// situations in which an RKey is known to not contain a wrapped locally-
// addressed Key. Whenever the Key which created the RKey is still available,
// it should be used instead.
func (rk RKey) AsRawKey() Key {
return Key(rk)
}
// Less compares two RKeys.
func (rk RKey) Less(otherRK RKey) bool {
return bytes.Compare(rk, otherRK) < 0
}
// Equal checks for byte-wise equality.
func (rk RKey) Equal(other []byte) bool {
return bytes.Equal(rk, other)
}
// Next returns the RKey that sorts immediately after the given one.
// The method may only take a shallow copy of the RKey, so both the
// receiver and the return value should be treated as immutable after.
func (rk RKey) Next() RKey {
return RKey(BytesNext(rk))
}
// PrefixEnd determines the end key given key as a prefix, that is the
// key that sorts precisely behind all keys starting with prefix: "1"
// is added to the final byte and the carry propagated. The special
// cases of nil and KeyMin always returns KeyMax.
func (rk RKey) PrefixEnd() RKey {
if len(rk) == 0 {
return RKeyMax
}
return RKey(bytesPrefixEnd(rk))
}
func (rk RKey) String() string {
return Key(rk).String()
}
// Key is a custom type for a byte string in proto
// messages which refer to Cockroach keys.
type Key []byte
// BytesNext returns the next possible byte slice, using the extra capacity
// of the provided slice if possible, and if not, appending an \x00.
func BytesNext(b []byte) []byte {
if cap(b) > len(b) {
bNext := b[:len(b)+1]
if bNext[len(bNext)-1] == 0 {
return bNext
}
}
// TODO(spencer): Do we need to enforce KeyMaxLength here?
// Switched to "make and copy" pattern in #4963 for performance.
bn := make([]byte, len(b)+1)
copy(bn, b)
bn[len(bn)-1] = 0
return bn
}
func bytesPrefixEnd(b []byte) []byte {
// Switched to "make and copy" pattern in #4963 for performance.
end := make([]byte, len(b))
copy(end, b)
for i := len(end) - 1; i >= 0; i-- {
end[i] = end[i] + 1
if end[i] != 0 {
return end[:i+1]
}
}
// This statement will only be reached if the key is already a
// maximal byte string (i.e. already \xff...).
return b
}
// Next returns the next key in lexicographic sort order. The method may only
// take a shallow copy of the Key, so both the receiver and the return
// value should be treated as immutable after.
func (k Key) Next() Key {
return Key(BytesNext(k))
}
// IsPrev is a more efficient version of k.Next().Equal(m).
func (k Key) IsPrev(m Key) bool {
l := len(m) - 1
return l == len(k) && m[l] == 0 && k.Equal(m[:l])
}
// PrefixEnd determines the end key given key as a prefix, that is the
// key that sorts precisely behind all keys starting with prefix: "1"
// is added to the final byte and the carry propagated. The special
// cases of nil and KeyMin always returns KeyMax.
func (k Key) PrefixEnd() Key {
if len(k) == 0 {
return Key(RKeyMax)
}
return Key(bytesPrefixEnd(k))
}
// Equal returns whether two keys are identical.
func (k Key) Equal(l Key) bool {
return bytes.Equal(k, l)
}
// Compare compares the two Keys.
func (k Key) Compare(b Key) int {
return bytes.Compare(k, b)
}
// String returns a string-formatted version of the key.
func (k Key) String() string {
// Leave valDirs unspecified such that values are pretty-printed
// with default encoding direction.
return k.StringWithDirs(nil /* valDirs */)
}
// StringWithDirs is the value encoding direction-aware version of String.
func (k Key) StringWithDirs(valDirs []encoding.Direction) string {
if PrettyPrintKey != nil {
return PrettyPrintKey(valDirs, k)
}
return fmt.Sprintf("%q", []byte(k))
}
// Format implements the fmt.Formatter interface.
func (k Key) Format(f fmt.State, verb rune) {
// Note: this implementation doesn't handle the width and precision
// specifiers such as "%20.10s".
if verb == 'x' {
fmt.Fprintf(f, "%x", []byte(k))
} else if PrettyPrintKey != nil {
fmt.Fprint(f, PrettyPrintKey(nil /* valDirs */, k))
} else {
fmt.Fprint(f, strconv.Quote(string(k)))
}
}
const (
checksumUninitialized = 0
checksumSize = 4
tagPos = checksumSize
headerSize = tagPos + 1
)
func (v Value) checksum() uint32 {
if len(v.RawBytes) < checksumSize {
return 0
}
_, u, err := encoding.DecodeUint32Ascending(v.RawBytes[:checksumSize])
if err != nil {
panic(err)
}
return u
}
func (v *Value) setChecksum(cksum uint32) {
if len(v.RawBytes) >= checksumSize {
encoding.EncodeUint32Ascending(v.RawBytes[:0], cksum)
}
}
// InitChecksum initializes a checksum based on the provided key and
// the contents of the value. If the value contains a byte slice, the
// checksum includes it directly.
//
// TODO(peter): This method should return an error if the Value is corrupted
// (e.g. the RawBytes field is > 0 but smaller than the header size).
func (v *Value) InitChecksum(key []byte) {
if v.RawBytes == nil {
return
}
// Should be uninitialized.
if v.checksum() != checksumUninitialized {
panic(fmt.Sprintf("initialized checksum = %x", v.checksum()))
}
v.setChecksum(v.computeChecksum(key))
}
// ClearChecksum clears the checksum value.
func (v *Value) ClearChecksum() {
v.setChecksum(0)
}
// Verify verifies the value's Checksum matches a newly-computed
// checksum of the value's contents. If the value's Checksum is not
// set the verification is a noop.
func (v Value) Verify(key []byte) error {
if n := len(v.RawBytes); n > 0 && n < headerSize {
return fmt.Errorf("%s: invalid header size: %d", Key(key), n)
}
if sum := v.checksum(); sum != 0 {
if computedSum := v.computeChecksum(key); computedSum != sum {
return fmt.Errorf("%s: invalid checksum (%x) value [% x]",
Key(key), computedSum, v.RawBytes)
}
}
return nil
}
// ShallowClone returns a shallow clone of the receiver.
func (v *Value) ShallowClone() *Value {
if v == nil {
return nil
}
t := *v
return &t
}
// IsPresent returns true if the value is present (existent and not a tombstone).
func (v *Value) IsPresent() bool {
return v != nil && len(v.RawBytes) != 0
}
// MakeValueFromString returns a value with bytes and tag set.
func MakeValueFromString(s string) Value {
v := Value{}
v.SetString(s)
return v
}
// MakeValueFromBytes returns a value with bytes and tag set.
func MakeValueFromBytes(bs []byte) Value {
v := Value{}
v.SetBytes(bs)
return v
}
// MakeValueFromBytesAndTimestamp returns a value with bytes, timestamp and
// tag set.
func MakeValueFromBytesAndTimestamp(bs []byte, t hlc.Timestamp) Value {
v := Value{Timestamp: t}
v.SetBytes(bs)
return v
}
// GetTag retrieves the value type.
func (v Value) GetTag() ValueType {
if len(v.RawBytes) <= tagPos {
return ValueType_UNKNOWN
}
return ValueType(v.RawBytes[tagPos])
}
func (v *Value) setTag(t ValueType) {
v.RawBytes[tagPos] = byte(t)
}
func (v Value) dataBytes() []byte {
return v.RawBytes[headerSize:]
}
// SetBytes sets the bytes and tag field of the receiver and clears the checksum.
func (v *Value) SetBytes(b []byte) {
v.RawBytes = make([]byte, headerSize+len(b))
copy(v.dataBytes(), b)
v.setTag(ValueType_BYTES)
}
// SetString sets the bytes and tag field of the receiver and clears the
// checksum. This is identical to SetBytes, but specialized for a string
// argument.
func (v *Value) SetString(s string) {
v.RawBytes = make([]byte, headerSize+len(s))
copy(v.dataBytes(), s)
v.setTag(ValueType_BYTES)
}
// SetFloat encodes the specified float64 value into the bytes field of the
// receiver, sets the tag and clears the checksum.
func (v *Value) SetFloat(f float64) {
v.RawBytes = make([]byte, headerSize+8)
encoding.EncodeUint64Ascending(v.RawBytes[headerSize:headerSize], math.Float64bits(f))
v.setTag(ValueType_FLOAT)
}
// SetBool encodes the specified bool value into the bytes field of the
// receiver, sets the tag and clears the checksum.
func (v *Value) SetBool(b bool) {
// 0 or 1 will always encode to a 1-byte long varint.
v.RawBytes = make([]byte, headerSize+1)
i := int64(0)
if b {
i = 1
}
_ = binary.PutVarint(v.RawBytes[headerSize:], i)
v.setTag(ValueType_INT)
}
// SetInt encodes the specified int64 value into the bytes field of the
// receiver, sets the tag and clears the checksum.
func (v *Value) SetInt(i int64) {
v.RawBytes = make([]byte, headerSize+binary.MaxVarintLen64)
n := binary.PutVarint(v.RawBytes[headerSize:], i)
v.RawBytes = v.RawBytes[:headerSize+n]
v.setTag(ValueType_INT)
}
// SetProto encodes the specified proto message into the bytes field of the
// receiver and clears the checksum. If the proto message is an
// InternalTimeSeriesData, the tag will be set to TIMESERIES rather than BYTES.
func (v *Value) SetProto(msg protoutil.Message) error {
msg = protoutil.MaybeFuzz(msg)
// All of the Cockroach protos implement MarshalTo and Size. So we marshal
// directly into the Value.RawBytes field instead of allocating a separate
// []byte and copying.
size := msg.Size()
v.RawBytes = make([]byte, headerSize+size)
if _, err := protoutil.MarshalToWithoutFuzzing(msg, v.RawBytes[headerSize:]); err != nil {
return err
}
// Special handling for timeseries data.
if _, ok := msg.(*InternalTimeSeriesData); ok {
v.setTag(ValueType_TIMESERIES)
} else {
v.setTag(ValueType_BYTES)
}
return nil
}
// SetTime encodes the specified time value into the bytes field of the
// receiver, sets the tag and clears the checksum.
func (v *Value) SetTime(t time.Time) {
const encodingSizeOverestimate = 11
v.RawBytes = make([]byte, headerSize, headerSize+encodingSizeOverestimate)
v.RawBytes = encoding.EncodeTimeAscending(v.RawBytes, t)
v.setTag(ValueType_TIME)
}
// SetDuration encodes the specified duration value into the bytes field of the
// receiver, sets the tag and clears the checksum.
func (v *Value) SetDuration(t duration.Duration) error {
var err error
v.RawBytes = make([]byte, headerSize, headerSize+encoding.EncodedDurationMaxLen)
v.RawBytes, err = encoding.EncodeDurationAscending(v.RawBytes, t)
if err != nil {
return err
}
v.setTag(ValueType_DURATION)
return nil
}
// SetDecimal encodes the specified decimal value into the bytes field of
// the receiver using Gob encoding, sets the tag and clears the checksum.
func (v *Value) SetDecimal(dec *apd.Decimal) error {
decSize := encoding.UpperBoundNonsortingDecimalSize(dec)
v.RawBytes = make([]byte, headerSize, headerSize+decSize)
v.RawBytes = encoding.EncodeNonsortingDecimal(v.RawBytes, dec)
v.setTag(ValueType_DECIMAL)
return nil
}
// SetTuple sets the tuple bytes and tag field of the receiver and clears the
// checksum.
func (v *Value) SetTuple(data []byte) {
// TODO(dan): Reuse this and stop allocating on every SetTuple call. Same for
// the other SetFoos.
v.RawBytes = make([]byte, headerSize+len(data))
copy(v.dataBytes(), data)
v.setTag(ValueType_TUPLE)
}
// GetBytes returns the bytes field of the receiver. If the tag is not
// BYTES an error will be returned.
func (v Value) GetBytes() ([]byte, error) {
if tag := v.GetTag(); tag != ValueType_BYTES {
return nil, fmt.Errorf("value type is not %s: %s", ValueType_BYTES, tag)
}
return v.dataBytes(), nil
}
// GetFloat decodes a float64 value from the bytes field of the receiver. If
// the bytes field is not 8 bytes in length or the tag is not FLOAT an error
// will be returned.
func (v Value) GetFloat() (float64, error) {
if tag := v.GetTag(); tag != ValueType_FLOAT {
return 0, fmt.Errorf("value type is not %s: %s", ValueType_FLOAT, tag)
}
dataBytes := v.dataBytes()
if len(dataBytes) != 8 {
return 0, fmt.Errorf("float64 value should be exactly 8 bytes: %d", len(dataBytes))
}
_, u, err := encoding.DecodeUint64Ascending(dataBytes)
if err != nil {
return 0, err
}
return math.Float64frombits(u), nil
}
// GetBool decodes a bool value from the bytes field of the receiver. If the
// tag is not INT (the tag used for bool values) or the value cannot be decoded
// an error will be returned.
func (v Value) GetBool() (bool, error) {
if tag := v.GetTag(); tag != ValueType_INT {
return false, fmt.Errorf("value type is not %s: %s", ValueType_INT, tag)
}
i, n := binary.Varint(v.dataBytes())
if n <= 0 {
return false, fmt.Errorf("int64 varint decoding failed: %d", n)
}
if i > 1 || i < 0 {
return false, fmt.Errorf("invalid bool: %d", i)
}
return i != 0, nil
}
// GetInt decodes an int64 value from the bytes field of the receiver. If the
// tag is not INT or the value cannot be decoded an error will be returned.
func (v Value) GetInt() (int64, error) {
if tag := v.GetTag(); tag != ValueType_INT {
return 0, fmt.Errorf("value type is not %s: %s", ValueType_INT, tag)
}
i, n := binary.Varint(v.dataBytes())
if n <= 0 {
return 0, fmt.Errorf("int64 varint decoding failed: %d", n)
}
return i, nil
}
// GetProto unmarshals the bytes field of the receiver into msg. If
// unmarshalling fails or the tag is not BYTES, an error will be
// returned.
func (v Value) GetProto(msg protoutil.Message) error {
expectedTag := ValueType_BYTES
// Special handling for ts data.
if _, ok := msg.(*InternalTimeSeriesData); ok {
expectedTag = ValueType_TIMESERIES
}
if tag := v.GetTag(); tag != expectedTag {
return fmt.Errorf("value type is not %s: %s", expectedTag, tag)
}
return protoutil.Unmarshal(v.dataBytes(), msg)
}
// GetTime decodes a time value from the bytes field of the receiver. If the
// tag is not TIME an error will be returned.
func (v Value) GetTime() (time.Time, error) {
if tag := v.GetTag(); tag != ValueType_TIME {
return time.Time{}, fmt.Errorf("value type is not %s: %s", ValueType_TIME, tag)
}
_, t, err := encoding.DecodeTimeAscending(v.dataBytes())
return t, err
}
// GetDuration decodes a duration value from the bytes field of the receiver. If
// the tag is not DURATION an error will be returned.
func (v Value) GetDuration() (duration.Duration, error) {
if tag := v.GetTag(); tag != ValueType_DURATION {
return duration.Duration{}, fmt.Errorf("value type is not %s: %s", ValueType_DURATION, tag)
}
_, t, err := encoding.DecodeDurationAscending(v.dataBytes())
return t, err
}
// GetDecimal decodes a decimal value from the bytes of the receiver. If the
// tag is not DECIMAL an error will be returned.
func (v Value) GetDecimal() (apd.Decimal, error) {
if tag := v.GetTag(); tag != ValueType_DECIMAL {
return apd.Decimal{}, fmt.Errorf("value type is not %s: %s", ValueType_DECIMAL, tag)
}
return encoding.DecodeNonsortingDecimal(v.dataBytes(), nil)
}
// GetTimeseries decodes an InternalTimeSeriesData value from the bytes
// field of the receiver. An error will be returned if the tag is not
// TIMESERIES or if decoding fails.
func (v Value) GetTimeseries() (InternalTimeSeriesData, error) {
ts := InternalTimeSeriesData{}
return ts, v.GetProto(&ts)
}
// GetTuple returns the tuple bytes of the receiver. If the tag is not TUPLE an
// error will be returned.
func (v Value) GetTuple() ([]byte, error) {
if tag := v.GetTag(); tag != ValueType_TUPLE {
return nil, fmt.Errorf("value type is not %s: %s", ValueType_TUPLE, tag)
}
return v.dataBytes(), nil
}
var crc32Pool = sync.Pool{
New: func() interface{} {
return crc32.NewIEEE()
},
}
func computeChecksum(key, rawBytes []byte, crc hash.Hash32) uint32 {
if len(rawBytes) < headerSize {
return 0
}
if _, err := crc.Write(key); err != nil {
panic(err)
}
if _, err := crc.Write(rawBytes[checksumSize:]); err != nil {
panic(err)
}
sum := crc.Sum32()
crc.Reset()
// We reserved the value 0 (checksumUninitialized) to indicate that a checksum
// has not been initialized. This reservation is accomplished by folding a
// computed checksum of 0 to the value 1.
if sum == checksumUninitialized {
return 1
}
return sum
}
// computeChecksum computes a checksum based on the provided key and
// the contents of the value.
func (v Value) computeChecksum(key []byte) uint32 {
crc := crc32Pool.Get().(hash.Hash32)
sum := computeChecksum(key, v.RawBytes, crc)
crc32Pool.Put(crc)
return sum
}
// PrettyPrint returns the value in a human readable format.
// e.g. `Put /Table/51/1/1/0 -> /TUPLE/2:2:Int/7/1:3:Float/6.28`
// In `1:3:Float/6.28`, the `1` is the column id diff as stored, `3` is the
// computed (i.e. not stored) actual column id, `Float` is the type, and `6.28`
// is the encoded value.
func (v Value) PrettyPrint() string {
var buf bytes.Buffer
t := v.GetTag()
buf.WriteRune('/')
buf.WriteString(t.String())
buf.WriteRune('/')
var err error
switch t {
case ValueType_TUPLE:
b := v.dataBytes()
var colID uint32
for i := 0; len(b) > 0; i++ {
if i != 0 {
buf.WriteRune('/')
}
_, _, colIDDiff, typ, err := encoding.DecodeValueTag(b)
if err != nil {
break
}
colID += colIDDiff
var s string
b, s, err = encoding.PrettyPrintValueEncoded(b)
if err != nil {
break
}
fmt.Fprintf(&buf, "%d:%d:%s/%s", colIDDiff, colID, typ, s)
}
case ValueType_INT:
var i int64
i, err = v.GetInt()
buf.WriteString(strconv.FormatInt(i, 10))
case ValueType_FLOAT:
var f float64
f, err = v.GetFloat()
buf.WriteString(strconv.FormatFloat(f, 'g', -1, 64))
case ValueType_BYTES:
var data []byte
data, err = v.GetBytes()
printable := len(bytes.TrimLeftFunc(data, unicode.IsPrint)) == 0
if printable {
buf.WriteString(string(data))
} else {
buf.WriteString(hex.EncodeToString(data))
}
case ValueType_TIME:
var t time.Time
t, err = v.GetTime()
buf.WriteString(t.UTC().Format(time.RFC3339Nano))
case ValueType_DECIMAL:
var d apd.Decimal
d, err = v.GetDecimal()
buf.WriteString(d.String())
case ValueType_DURATION:
var d duration.Duration
d, err = v.GetDuration()
buf.WriteString(d.String())
default:
err = errors.Errorf("unknown tag: %s", t)
}
if err != nil {
// Ignore the contents of buf and return directly.
return fmt.Sprintf("/<err: %s>", err)
}
return buf.String()
}
const (
// MinTxnPriority is the minimum allowed txn priority.
MinTxnPriority = 0
// MaxTxnPriority is the maximum allowed txn priority.
MaxTxnPriority = math.MaxInt32
)
// MakeTransaction creates a new transaction. The transaction key is
// composed using the specified baseKey (for locality with data
// affected by the transaction) and a random ID to guarantee
// uniqueness. The specified user-level priority is combined with a
// randomly chosen value to yield a final priority, used to settle
// write conflicts in a way that avoids starvation of long-running
// transactions (see Replica.PushTxn).
//
// baseKey can be nil, in which case it will be set when sending the first
// write.
func MakeTransaction(
name string,
baseKey Key,
userPriority UserPriority,
isolation enginepb.IsolationType,
now hlc.Timestamp,
maxOffsetNs int64,
) Transaction {
u := uuid.MakeV4()
var maxTS hlc.Timestamp
if maxOffsetNs == timeutil.ClocklessMaxOffset {
// For clockless reads, use the largest possible maxTS. This means we'll
// always restart if we see something in our future (but we do so at
// most once thanks to ObservedTimestamps).
maxTS.WallTime = math.MaxInt64
} else {
maxTS = now.Add(maxOffsetNs, 0)
}
return Transaction{
TxnMeta: enginepb.TxnMeta{
Key: baseKey,
ID: u,
Isolation: isolation,
Timestamp: now,
Priority: MakePriority(userPriority),
Sequence: 1,
},
Name: name,
LastHeartbeat: now,
OrigTimestamp: now,
MaxTimestamp: maxTS,
}
}
// LastActive returns the last timestamp at which client activity definitely
// occurred, i.e. the maximum of OrigTimestamp and LastHeartbeat.
func (t Transaction) LastActive() hlc.Timestamp {
ts := t.LastHeartbeat
if ts.Less(t.OrigTimestamp) {
ts = t.OrigTimestamp
}
return ts
}
// Clone creates a copy of the given transaction. The copy is "mostly" deep,
// but does share pieces of memory with the original such as Key, ID and the
// keys with the intent spans.
func (t Transaction) Clone() Transaction {
mt := t.ObservedTimestamps
if mt != nil {
t.ObservedTimestamps = make([]ObservedTimestamp, len(mt))
copy(t.ObservedTimestamps, mt)
}
// Note that we're not cloning the span keys under the assumption that the
// keys themselves are not mutable.
t.Intents = append([]Span(nil), t.Intents...)
return t
}
// AssertInitialized crashes if the transaction is not initialized.
func (t *Transaction) AssertInitialized(ctx context.Context) {
if t.ID == (uuid.UUID{}) ||
t.OrigTimestamp == (hlc.Timestamp{}) ||
t.Timestamp == (hlc.Timestamp{}) {
log.Fatalf(ctx, "uninitialized txn: %s", t)
}
}
// MakePriority generates a random priority value, biased by the specified
// userPriority. If userPriority=100, the random priority will be 100x more
// likely to be greater than if userPriority=1. If userPriority = 0.1, the
// random priority will be 1/10th as likely to be greater than if
// userPriority=NormalUserPriority ( = 1). Balance is achieved when
// userPriority=NormalUserPriority, in which case the priority chosen is
// unbiased.
//
// If userPriority is less than or equal to MinUserPriority, returns
// MinTxnPriority; if greater than or equal to MaxUserPriority, returns
// MaxTxnPriority. If userPriority is 0, returns NormalUserPriority.
func MakePriority(userPriority UserPriority) int32 {
// A currently undocumented feature allows an explicit priority to
// be set by specifying priority < 1. The explicit priority is
// simply -userPriority in this case. This is hacky, but currently
// used for unittesting. Perhaps this should be documented and allowed.
if userPriority < 0 {
if -userPriority > UserPriority(math.MaxInt32) {
panic(fmt.Sprintf("cannot set explicit priority to a value less than -%d", math.MaxInt32))
}
return int32(-userPriority)
} else if userPriority == 0 {
userPriority = NormalUserPriority
} else if userPriority >= MaxUserPriority {
return MaxTxnPriority
} else if userPriority <= MinUserPriority {
return MinTxnPriority
}
// We generate random values which are biased according to priorities. If v1 is a value
// generated for priority p1 and v2 is a value of priority v2, we want the ratio of wins vs
// losses to be the same with the ratio of priorities:
//
// P[ v1 > v2 ] p1 p1
// ------------ = -- or, equivalently: P[ v1 > v2 ] = -------
// P[ v2 < v1 ] p2 p1 + p2
//
//
// For example, priority 10 wins 10 out of 11 times over priority 1, and it wins 100 out of 101
// times over priority 0.1.
//
//
// We use the exponential distribution. This distribution has the probability density function
// PDF_lambda(x) = lambda * exp(-lambda * x)
// and the cumulative distribution function (i.e. probability that a random value is smaller
// than x):
// CDF_lambda(x) = Integral_0^x PDF_lambda(x) dx
// = 1 - exp(-lambda * x)
//
// Let's assume we generate x from the exponential distribution with the lambda rate set to
// l1 and we generate y from the distribution with the rate set to l2. The probability that x
// wins is:
// P[ x > y ] = Integral_0^inf Integral_0^x PDF_l1(x) PDF_l2(y) dy dx
// = Integral_0^inf PDF_l1(x) Integral_0^x PDF_l2(y) dy dx
// = Integral_0^inf PDF_l1(x) CDF_l2(x) dx
// = Integral_0^inf PDF_l1(x) (1 - exp(-l2 * x)) dx
// = 1 - Integral_0^inf l1 * exp(-(l1+l2) * x) dx
// = 1 - l1 / (l1 + l2) * Integral_0^inf PDF_(l1+l2)(x) dx
// = 1 - l1 / (l1 + l2)
// = l2 / (l1 + l2)
//
// We want this probability to be p1 / (p1 + p2) which we can get by setting
// l1 = 1 / p1
// l2 = 1 / p2
// It's easy to verify that (1/p2) / (1/p1 + 1/p2) = p1 / (p2 + p1).
//
// We can generate an exponentially distributed value using (rand.ExpFloat64() / lambda).
// In our case this works out to simply rand.ExpFloat64() * userPriority.
val := rand.ExpFloat64() * float64(userPriority)
// To convert to an integer, we scale things to accommodate a few (5) standard deviations for
// the maximum priority. The choice of the value is a trade-off between loss of resolution for
// low priorities and overflow (capping the value to MaxInt32) for high priorities.
//
// For userPriority=MaxUserPriority, the probability of overflow is 0.7%.
// For userPriority=(MaxUserPriority/2), the probability of overflow is 0.005%.
val = (val / (5 * float64(MaxUserPriority))) * math.MaxInt32
if val <= MinTxnPriority {
return MinTxnPriority + 1
} else if val >= MaxTxnPriority {
return MaxTxnPriority - 1
}
return int32(val)
}
// Restart reconfigures a transaction for restart. The epoch is
// incremented for an in-place restart. The timestamp of the
// transaction on restart is set to the maximum of the transaction's
// timestamp and the specified timestamp.
func (t *Transaction) Restart(
userPriority UserPriority, upgradePriority int32, timestamp hlc.Timestamp,
) {
t.BumpEpoch()
if t.Timestamp.Less(timestamp) {
t.Timestamp = timestamp
}
// Set original timestamp to current timestamp on restart.
t.OrigTimestamp = t.Timestamp
// Upgrade priority to the maximum of:
// - the current transaction priority
// - a random priority created from userPriority
// - the conflicting transaction's upgradePriority
t.UpgradePriority(MakePriority(userPriority))
t.UpgradePriority(upgradePriority)
t.WriteTooOld = false
t.RetryOnPush = false
t.Sequence = 0
}
// BumpEpoch increments the transaction's epoch, allowing for an in-place
// restart. This invalidates all write intents previously written at lower
// epochs.
func (t *Transaction) BumpEpoch() {
if t.Epoch == 0 {
t.EpochZeroTimestamp = t.OrigTimestamp
}
t.Epoch++
}
// InclusiveTimeBounds returns start and end timestamps such that all intents written as
// part of this transaction have a timestamp in the interval [start, end].
func (t *Transaction) InclusiveTimeBounds() (hlc.Timestamp, hlc.Timestamp) {
min := t.OrigTimestamp
max := t.Timestamp
if t.Epoch != 0 {
if min.Less(t.EpochZeroTimestamp) {
panic(fmt.Sprintf("orig timestamp %s less than epoch zero %s", min, t.EpochZeroTimestamp))
}
min = t.EpochZeroTimestamp
}
return min, max
}
// Update ratchets priority, timestamp and original timestamp values (among
// others) for the transaction. If t.ID is empty, then the transaction is
// copied from o.
func (t *Transaction) Update(o *Transaction) {
if o == nil {
return
}
o.AssertInitialized(context.TODO())
if t.ID == (uuid.UUID{}) {
*t = o.Clone()
return
}
if len(t.Key) == 0 {
t.Key = o.Key
}
if o.Status != PENDING {
t.Status = o.Status
}
// If the epoch or refreshed timestamp move forward, overwrite
// WriteTooOld and RetryOnPush, otherwise the flags are cumulative.
if t.Epoch < o.Epoch || t.RefreshedTimestamp.Less(o.RefreshedTimestamp) {
t.WriteTooOld = o.WriteTooOld
t.RetryOnPush = o.RetryOnPush
} else {
t.WriteTooOld = t.WriteTooOld || o.WriteTooOld
t.RetryOnPush = t.RetryOnPush || o.RetryOnPush
}
if t.Epoch < o.Epoch {
t.Epoch = o.Epoch
}
t.Timestamp.Forward(o.Timestamp)
t.LastHeartbeat.Forward(o.LastHeartbeat)
t.OrigTimestamp.Forward(o.OrigTimestamp)
t.MaxTimestamp.Forward(o.MaxTimestamp)
t.RefreshedTimestamp.Forward(o.RefreshedTimestamp)
// Absorb the collected clock uncertainty information.
for _, v := range o.ObservedTimestamps {
t.UpdateObservedTimestamp(v.NodeID, v.Timestamp)
}
t.UpgradePriority(o.Priority)
// We can't assert against regression here since it can actually happen
// that we update from a transaction which isn't Writing.
t.Writing = t.Writing || o.Writing
if t.Sequence < o.Sequence {
t.Sequence = o.Sequence
}
if len(o.Intents) > 0 {
t.Intents = o.Intents
}
// On update, set epoch zero timestamp to the minimum seen by either txn.
if o.EpochZeroTimestamp != (hlc.Timestamp{}) {
if t.EpochZeroTimestamp == (hlc.Timestamp{}) || o.EpochZeroTimestamp.Less(t.EpochZeroTimestamp) {
t.EpochZeroTimestamp = o.EpochZeroTimestamp
}
}
}
// UpgradePriority sets transaction priority to the maximum of current
// priority and the specified minPriority. The exception is if the
// current priority is set to the minimum, in which case the minimum
// is preserved.
func (t *Transaction) UpgradePriority(minPriority int32) {
if minPriority > t.Priority && t.Priority != MinTxnPriority {
t.Priority = minPriority
}
}
// IsSerializable returns whether this transaction uses serializable
// isolation.
func (t *Transaction) IsSerializable() bool {
return t != nil && t.Isolation == enginepb.SERIALIZABLE
}
// String formats transaction into human readable string.
func (t Transaction) String() string {
var buf bytes.Buffer
// Compute priority as a floating point number from 0-100 for readability.
floatPri := 100 * float64(t.Priority) / float64(math.MaxInt32)
if len(t.Name) > 0 {
fmt.Fprintf(&buf, "%q ", t.Name)
}
fmt.Fprintf(&buf, "id=%s key=%s rw=%t pri=%.8f iso=%s stat=%s epo=%d "+
"ts=%s orig=%s max=%s wto=%t rop=%t seq=%d",
t.Short(), Key(t.Key), t.Writing, floatPri, t.Isolation, t.Status, t.Epoch, t.Timestamp,
t.OrigTimestamp, t.MaxTimestamp, t.WriteTooOld, t.RetryOnPush, t.Sequence)
if ni := len(t.Intents); t.Status != PENDING && ni > 0 {
fmt.Fprintf(&buf, " int=%d", ni)
}
return buf.String()
}
// ResetObservedTimestamps clears out all timestamps recorded from individual
// nodes.
func (t *Transaction) ResetObservedTimestamps() {
t.ObservedTimestamps = nil
}
// UpdateObservedTimestamp stores a timestamp off a node's clock for future
// operations in the transaction. When multiple calls are made for a single
// nodeID, the lowest timestamp prevails.
func (t *Transaction) UpdateObservedTimestamp(nodeID NodeID, maxTS hlc.Timestamp) {
// Fast path optimization for either no observed timestamps or
// exactly one, for the same nodeID as we're updating.
if l := len(t.ObservedTimestamps); l == 0 {
t.ObservedTimestamps = []ObservedTimestamp{{NodeID: nodeID, Timestamp: maxTS}}
return
} else if l == 1 && t.ObservedTimestamps[0].NodeID == nodeID {
if maxTS.Less(t.ObservedTimestamps[0].Timestamp) {
t.ObservedTimestamps = []ObservedTimestamp{{NodeID: nodeID, Timestamp: maxTS}}