-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
data.go
2369 lines (2153 loc) · 76.9 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.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package roachpb
import (
"bytes"
"context"
"encoding/binary"
"encoding/hex"
"fmt"
"hash"
"hash/crc32"
"math"
"math/rand"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/cockroachdb/apd/v2"
"github.com/cockroachdb/cockroach/pkg/geo"
"github.com/cockroachdb/cockroach/pkg/geo/geopb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/concurrency/lock"
"github.com/cockroachdb/cockroach/pkg/storage/enginepb"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/bitarray"
"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/timetz"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/redact"
"go.etcd.io/etcd/raft/raftpb"
)
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().
//
// RKey stands for "resolved key," as in a key whose address has been resolved.
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. That is, it must only be used when the original Key was not a
// local 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 returns true if receiver < otherRK.
func (rk RKey) Less(otherRK RKey) bool {
return rk.Compare(otherRK) < 0
}
// Compare compares the two RKeys.
func (rk RKey) Compare(other RKey) int {
return bytes.Compare(rk, other)
}
// 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()
}
// StringWithDirs - see Key.String.WithDirs.
func (rk RKey) StringWithDirs(valDirs []encoding.Direction, maxLen int) string {
return Key(rk).StringWithDirs(valDirs, maxLen)
}
// 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 {
return k.StringWithDirs(nil /* valDirs */, 0 /* maxLen */)
}
// StringWithDirs is the value encoding direction-aware version of String.
//
// Args:
// valDirs: The direction for the key's components, generally needed for correct
// decoding. If nil, the values are pretty-printed with default encoding
// direction.
// maxLen: If not 0, only the first maxLen chars from the decoded key are
// returned, plus a "..." suffix.
func (k Key) StringWithDirs(valDirs []encoding.Direction, maxLen int) string {
var s string
if PrettyPrintKey != nil {
s = PrettyPrintKey(valDirs, k)
} else {
s = fmt.Sprintf("%q", []byte(k))
}
if maxLen != 0 && len(s) > maxLen {
return s[0:maxLen] + "..."
}
return s
}
// 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 err := v.VerifyHeader(); err != nil {
return err
}
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
}
// VerifyHeader checks that, if the Value is not empty, it includes a header.
func (v Value) VerifyHeader() error {
if n := len(v.RawBytes); n > 0 && n < headerSize {
return errors.Errorf("invalid header size: %d", n)
}
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:]
}
// TagAndDataBytes returns the value's tag and data (no checksum, no timestamp).
// This is suitable to be used as the expected value in a CPut.
func (v Value) TagAndDataBytes() []byte {
return v.RawBytes[tagPos:]
}
func (v *Value) ensureRawBytes(size int) {
if cap(v.RawBytes) < size {
v.RawBytes = make([]byte, size)
return
}
v.RawBytes = v.RawBytes[:size]
v.setChecksum(checksumUninitialized)
}
// EqualTagAndData returns a boolean reporting whether the receiver and the parameter
// have equivalent byte values. This check ignores the optional checksum field
// in the Values' byte slices, returning only whether the Values have the same
// tag and encoded data.
//
// This method should be used whenever the raw bytes of two Values are being
// compared instead of comparing the RawBytes slices directly because it ignores
// the checksum header, which is optional.
func (v Value) EqualTagAndData(o Value) bool {
return bytes.Equal(v.TagAndDataBytes(), o.TagAndDataBytes())
}
// SetBytes copies the bytes and tag field to the receiver and clears the
// checksum.
func (v *Value) SetBytes(b []byte) {
v.ensureRawBytes(headerSize + len(b))
copy(v.dataBytes(), b)
v.setTag(ValueType_BYTES)
}
// SetTagAndData copies the bytes and tag field to the receiver and clears the
// checksum. As opposed to SetBytes, b is assumed to contain the tag too, not
// just the data.
func (v *Value) SetTagAndData(b []byte) {
v.ensureRawBytes(checksumSize + len(b))
copy(v.TagAndDataBytes(), b)
}
// 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.ensureRawBytes(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.ensureRawBytes(headerSize + 8)
encoding.EncodeUint64Ascending(v.RawBytes[headerSize:headerSize], math.Float64bits(f))
v.setTag(ValueType_FLOAT)
}
// SetGeo encodes the specified geo value into the bytes field of the
// receiver, sets the tag and clears the checksum.
func (v *Value) SetGeo(so geopb.SpatialObject) error {
bytes, err := protoutil.Marshal(&so)
if err != nil {
return err
}
v.ensureRawBytes(headerSize + len(bytes))
copy(v.dataBytes(), bytes)
v.setTag(ValueType_GEO)
return nil
}
// SetBox2D encodes the specified Box2D value into the bytes field of the
// receiver, sets the tag and clears the checksum.
func (v *Value) SetBox2D(b geo.CartesianBoundingBox) {
v.ensureRawBytes(headerSize + 32)
encoding.EncodeUint64Ascending(v.RawBytes[headerSize:headerSize], math.Float64bits(b.LoX))
encoding.EncodeUint64Ascending(v.RawBytes[headerSize+8:headerSize+8], math.Float64bits(b.HiX))
encoding.EncodeUint64Ascending(v.RawBytes[headerSize+16:headerSize+16], math.Float64bits(b.LoY))
encoding.EncodeUint64Ascending(v.RawBytes[headerSize+24:headerSize+24], math.Float64bits(b.HiY))
v.setTag(ValueType_BOX2D)
}
// 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.ensureRawBytes(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.ensureRawBytes(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 {
// 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.
v.ensureRawBytes(headerSize + msg.Size())
if _, err := protoutil.MarshalTo(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.ensureRawBytes(headerSize + encodingSizeOverestimate)
v.RawBytes = encoding.EncodeTimeAscending(v.RawBytes[:headerSize], t)
v.setTag(ValueType_TIME)
}
// SetTimeTZ encodes the specified time value into the bytes field of the
// receiver, sets the tag and clears the checksum.
func (v *Value) SetTimeTZ(t timetz.TimeTZ) {
v.ensureRawBytes(headerSize + encoding.EncodedTimeTZMaxLen)
v.RawBytes = encoding.EncodeTimeTZAscending(v.RawBytes[:headerSize], t)
v.setTag(ValueType_TIMETZ)
}
// 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.ensureRawBytes(headerSize + encoding.EncodedDurationMaxLen)
v.RawBytes, err = encoding.EncodeDurationAscending(v.RawBytes[:headerSize], t)
if err != nil {
return err
}
v.setTag(ValueType_DURATION)
return nil
}
// SetBitArray encodes the specified bit array value into the bytes field of the
// receiver, sets the tag and clears the checksum.
func (v *Value) SetBitArray(t bitarray.BitArray) {
words, _ := t.EncodingParts()
v.ensureRawBytes(headerSize + encoding.MaxNonsortingUvarintLen + 8*len(words))
v.RawBytes = encoding.EncodeUntaggedBitArrayValue(v.RawBytes[:headerSize], t)
v.setTag(ValueType_BITARRAY)
}
// 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.ensureRawBytes(headerSize + decSize)
v.RawBytes = encoding.EncodeNonsortingDecimal(v.RawBytes[:headerSize], 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) {
v.ensureRawBytes(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
}
// GetGeo decodes a geo value from the bytes field of the receiver. If the
// tag is not GEO an error will be returned.
func (v Value) GetGeo() (geopb.SpatialObject, error) {
if tag := v.GetTag(); tag != ValueType_GEO {
return geopb.SpatialObject{}, fmt.Errorf("value type is not %s: %s", ValueType_GEO, tag)
}
var ret geopb.SpatialObject
err := protoutil.Unmarshal(v.dataBytes(), &ret)
return ret, err
}
// GetBox2D decodes a geo value from the bytes field of the receiver. If the
// tag is not BOX2D an error will be returned.
func (v Value) GetBox2D() (geo.CartesianBoundingBox, error) {
box := geo.CartesianBoundingBox{}
if tag := v.GetTag(); tag != ValueType_BOX2D {
return box, fmt.Errorf("value type is not %s: %s", ValueType_BOX2D, tag)
}
dataBytes := v.dataBytes()
if len(dataBytes) != 32 {
return box, fmt.Errorf("float64 value should be exactly 32 bytes: %d", len(dataBytes))
}
var err error
var val uint64
dataBytes, val, err = encoding.DecodeUint64Ascending(dataBytes)
if err != nil {
return box, err
}
box.LoX = math.Float64frombits(val)
dataBytes, val, err = encoding.DecodeUint64Ascending(dataBytes)
if err != nil {
return box, err
}
box.HiX = math.Float64frombits(val)
dataBytes, val, err = encoding.DecodeUint64Ascending(dataBytes)
if err != nil {
return box, err
}
box.LoY = math.Float64frombits(val)
_, val, err = encoding.DecodeUint64Ascending(dataBytes)
if err != nil {
return box, err
}
box.HiY = math.Float64frombits(val)
return box, 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
}
// GetTimeTZ decodes a time value from the bytes field of the receiver. If the
// tag is not TIMETZ an error will be returned.
func (v Value) GetTimeTZ() (timetz.TimeTZ, error) {
if tag := v.GetTag(); tag != ValueType_TIMETZ {
return timetz.TimeTZ{}, fmt.Errorf("value type is not %s: %s", ValueType_TIMETZ, tag)
}
_, t, err := encoding.DecodeTimeTZAscending(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
}
// GetBitArray decodes a bit array value from the bytes field of the receiver. If
// the tag is not BITARRAY an error will be returned.
func (v Value) GetBitArray() (bitarray.BitArray, error) {
if tag := v.GetTag(); tag != ValueType_BITARRAY {
return bitarray.BitArray{}, fmt.Errorf("value type is not %s: %s", ValueType_BITARRAY, tag)
}
_, t, err := encoding.DecodeUntaggedBitArrayValue(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)
}
// GetDecimalInto decodes a decimal value from the bytes of the receiver,
// writing it directly into the provided non-null apd.Decimal. If the
// tag is not DECIMAL an error will be returned.
func (v Value) GetDecimalInto(d *apd.Decimal) error {
if tag := v.GetTag(); tag != ValueType_DECIMAL {
return fmt.Errorf("value type is not %s: %s", ValueType_DECIMAL, tag)
}
return encoding.DecodeIntoNonsortingDecimal(d, 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{}
// GetProto mutates its argument. `return ts, v.GetProto(&ts)`
// happens to work in gc, but does not work in gccgo.
//
// See https://github.com/golang/go/issues/23188.
err := v.GetProto(&ts)
return ts, err
}
// 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 {
if len(v.RawBytes) == 0 {
return "/<empty>"
}
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()
if encoding.PrintableBytes(data) {
buf.WriteString(string(data))
} else {
buf.WriteString("0x")
buf.WriteString(hex.EncodeToString(data))
}
case ValueType_BITARRAY:
var data bitarray.BitArray
data, err = v.GetBitArray()
buf.WriteByte('B')
data.Format(&buf)
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.StringNanos())
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()
}
// IsFinalized determines whether the transaction status is in a finalized
// state. A finalized state is terminal, meaning that once a transaction
// enters one of these states, it will never leave it.
func (ts TransactionStatus) IsFinalized() bool {
return ts == COMMITTED || ts == ABORTED
}
var _ errors.SafeMessager = Transaction{}
// 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, now hlc.Timestamp, maxOffsetNs int64,
) Transaction {
u := uuid.FastMakeV4()
maxTS := now.Add(maxOffsetNs, 0)
return Transaction{
TxnMeta: enginepb.TxnMeta{
Key: baseKey,
ID: u,
WriteTimestamp: now,
MinTimestamp: now,
Priority: MakePriority(userPriority),
Sequence: 0, // 1-indexed, incremented before each Request
},
Name: name,
LastHeartbeat: now,
ReadTimestamp: now,
MaxTimestamp: maxTS,
}
}
// LastActive returns the last timestamp at which client activity definitely
// occurred, i.e. the maximum of ReadTimestamp and LastHeartbeat.
func (t Transaction) LastActive() hlc.Timestamp {
ts := t.LastHeartbeat
ts.Forward(t.ReadTimestamp)
return ts
}
// Clone creates a copy of the given transaction. The copy is shallow because
// none of the references held by a transaction allow interior mutability.
func (t Transaction) Clone() *Transaction {
return &t
}
// AssertInitialized crashes if the transaction is not initialized.
func (t *Transaction) AssertInitialized(ctx context.Context) {
if t.ID == (uuid.UUID{}) || t.WriteTimestamp == (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) enginepb.TxnPriority {
// 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 enginepb.TxnPriority(-userPriority)
} else if userPriority == 0 {
userPriority = NormalUserPriority
} else if userPriority >= MaxUserPriority {
return enginepb.MaxTxnPriority
} else if userPriority <= MinUserPriority {
return enginepb.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%.