forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 1
/
key.go
356 lines (299 loc) · 9.33 KB
/
key.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
// Copyright 2012, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package key
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"sort"
"strings"
pb "github.com/youtube/vitess/go/vt/proto/topodata"
)
//
// KeyspaceId definitions
//
// MinKey is smaller than all KeyspaceId (the value really is).
var MinKey = KeyspaceId("")
// MaxKey is bigger than all KeyspaceId (by convention).
var MaxKey = KeyspaceId("")
// KeyspaceId is the type we base sharding on.
type KeyspaceId string
//go:generate bsongen -file $GOFILE -type KeyspaceId -o keyspace_id_bson.go
// Hex prints a KeyspaceId in lower case hex.
func (kid KeyspaceId) Hex() HexKeyspaceId {
return HexKeyspaceId(hex.EncodeToString([]byte(kid)))
}
func (kid KeyspaceId) String() string {
return string(kid.Hex())
}
// MarshalJSON turns a KeyspaceId into json (using hex encoding).
func (kid KeyspaceId) MarshalJSON() ([]byte, error) {
return []byte("\"" + string(kid.Hex()) + "\""), nil
}
// UnmarshalJSON reads a KeyspaceId from json (hex decoding).
func (kid *KeyspaceId) UnmarshalJSON(data []byte) (err error) {
*kid, err = HexKeyspaceId(data[1 : len(data)-1]).Unhex()
return err
}
//
// Uint64Key definitions
//
// Uint64Key is a uint64 that can be converted into a KeyspaceId.
type Uint64Key uint64
func (i Uint64Key) String() string {
buf := new(bytes.Buffer)
binary.Write(buf, binary.BigEndian, uint64(i))
return buf.String()
}
// KeyspaceId returns the KeyspaceId associated with a Uint64Key.
func (i Uint64Key) KeyspaceId() KeyspaceId {
return KeyspaceId(i.String())
}
// Bytes returns the keyspace id (as bytes) associated with a Uint64Key.
func (i Uint64Key) Bytes() []byte {
buf := new(bytes.Buffer)
binary.Write(buf, binary.BigEndian, uint64(i))
return buf.Bytes()
}
// HexKeyspaceId is the hex represention of a KeyspaceId.
type HexKeyspaceId string
// Unhex converts a HexKeyspaceId into a KeyspaceId (hex decoding).
func (hkid HexKeyspaceId) Unhex() (KeyspaceId, error) {
b, err := hex.DecodeString(string(hkid))
if err != nil {
return KeyspaceId(""), err
}
return KeyspaceId(string(b)), nil
}
//
// KeyspaceIdType definitions
//
// KeyspaceIdType represents the type of the KeyspaceId.
// Usually we don't care, but some parts of the code will need that info.
type KeyspaceIdType string
//go:generate bsongen -file $GOFILE -type KeyspaceIdType -o keyspace_id_type_bson.go
const (
// unset - no type for this KeyspaceId
KIT_UNSET = KeyspaceIdType("")
// uint64 - a uint64 value is used
// this is represented as 'unsigned bigint' in mysql
KIT_UINT64 = KeyspaceIdType("uint64")
// bytes - a string of bytes is used
// this is represented as 'varbinary' in mysql
KIT_BYTES = KeyspaceIdType("bytes")
)
var AllKeyspaceIdTypes = []KeyspaceIdType{
KIT_UNSET,
KIT_UINT64,
KIT_BYTES,
}
// IsKeyspaceIdTypeInList returns true if the given type is in the list.
// Use it with AllKeyspaceIdTypes for instance.
func IsKeyspaceIdTypeInList(typ KeyspaceIdType, types []KeyspaceIdType) bool {
for _, t := range types {
if typ == t {
return true
}
}
return false
}
// ParseKeyspaceIDType parses the keyspace id type into the enum
func ParseKeyspaceIDType(param string) (pb.KeyspaceIdType, error) {
if param == "" {
return pb.KeyspaceIdType_UNSET, nil
}
value, ok := pb.KeyspaceIdType_value[strings.ToUpper(param)]
if !ok {
return pb.KeyspaceIdType_UNSET, fmt.Errorf("unknown KeyspaceIdType %v", param)
}
return pb.KeyspaceIdType(value), nil
}
//
// KeyRange definitions
//
// KeyRange is an interval of KeyspaceId values. It contains Start,
// but excludes End. In other words, it is: [Start, End)
type KeyRange struct {
Start KeyspaceId
End KeyspaceId
}
//go:generate bsongen -file $GOFILE -type KeyRange -o key_range_bson.go
func (kr KeyRange) Contains(i KeyspaceId) bool {
return kr.Start <= i && (kr.End == MaxKey || i < kr.End)
}
// KeyRangeContains returns true if the provided id is in the keyrange.
func KeyRangeContains(kr *pb.KeyRange, id []byte) bool {
if kr == nil {
return true
}
return string(kr.Start) <= string(id) &&
(len(kr.End) == 0 || string(id) < string(kr.End))
}
func (kr KeyRange) String() string {
return fmt.Sprintf("{Start: %v, End: %v}", string(kr.Start.Hex()), string(kr.End.Hex()))
}
// ParseKeyRangeParts parses a start and end hex values and build a proto KeyRange
func ParseKeyRangeParts(start, end string) (*pb.KeyRange, error) {
s, err := hex.DecodeString(start)
if err != nil {
return nil, err
}
e, err := hex.DecodeString(end)
if err != nil {
return nil, err
}
return &pb.KeyRange{Start: s, End: e}, nil
}
// KeyRangeString prints a pb.KeyRange
func KeyRangeString(k *pb.KeyRange) string {
if k == nil {
return "<nil>"
}
return hex.EncodeToString(k.Start) + "-" + hex.EncodeToString(k.End)
}
// KeyRangeIsPartial returns true if the KeyRange does not cover the entire space.
func KeyRangeIsPartial(kr *pb.KeyRange) bool {
if kr == nil {
return false
}
return !(len(kr.Start) == 0 && len(kr.End) == 0)
}
// KeyRangeEqual returns true if both key ranges cover the same area
func KeyRangeEqual(left, right *pb.KeyRange) bool {
if left == nil {
return right == nil || (len(right.Start) == 0 && len(right.End) == 0)
}
if right == nil {
return len(left.Start) == 0 && len(left.End) == 0
}
return string(left.Start) == string(right.Start) &&
string(left.End) == string(right.End)
}
// KeyRangeStartEqual returns true if both key ranges have the same start
func KeyRangeStartEqual(left, right *pb.KeyRange) bool {
if left == nil {
return right == nil || len(right.Start) == 0
}
if right == nil {
return len(left.Start) == 0
}
return string(left.Start) == string(right.Start)
}
// KeyRangeEndEqual returns true if both key ranges have the same end
func KeyRangeEndEqual(left, right *pb.KeyRange) bool {
if left == nil {
return right == nil || len(right.End) == 0
}
if right == nil {
return len(left.End) == 0
}
return string(left.End) == string(right.End)
}
// For more info on the following functions, see:
// See: http://stackoverflow.com/questions/4879315/what-is-a-tidy-algorithm-to-find-overlapping-intervals
// two segments defined as (a,b) and (c,d) (with a<b and c<d):
// intersects = (b > c) && (a < d)
// overlap = min(b, d) - max(c, a)
// KeyRangesIntersect returns true if some Keyspace values exist in both ranges.
func KeyRangesIntersect(first, second *pb.KeyRange) bool {
if first == nil || second == nil {
return true
}
return (len(first.End) == 0 || string(second.Start) < string(first.End)) &&
(len(second.End) == 0 || string(first.Start) < string(second.End))
}
// KeyRangesOverlap returns the overlap between two KeyRanges.
// They need to overlap, otherwise an error is returned.
func KeyRangesOverlap(first, second *pb.KeyRange) (*pb.KeyRange, error) {
if !KeyRangesIntersect(first, second) {
return nil, fmt.Errorf("KeyRanges %v and %v don't overlap", first, second)
}
if first == nil {
return second, nil
}
if second == nil {
return first, nil
}
// compute max(c,a) and min(b,d)
// start with (a,b)
result := &(*first)
// if c > a, then use c
if string(second.Start) > string(first.Start) {
result.Start = second.Start
}
// if b is maxed out, or
// (d is not maxed out and d < b)
// ^ valid test as neither b nor d are max
// then use d
if len(first.End) == 0 || (len(second.End) != 0 && string(second.End) < string(first.End)) {
result.End = second.End
}
return result, nil
}
//
// KeyspaceIdArray definitions
//
// KeyspaceIdArray is an array of KeyspaceId that can be sorted
// We use it only if we need to sort []KeyspaceId
type KeyspaceIdArray []KeyspaceId
func (p KeyspaceIdArray) Len() int { return len(p) }
func (p KeyspaceIdArray) Less(i, j int) bool {
return p[i] < p[j]
}
func (p KeyspaceIdArray) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
func (p KeyspaceIdArray) Sort() { sort.Sort(p) }
//
// KeyRangeArray definitions
//
// KeyRangeArray is an array of KeyRange that can be sorted
// We use it only if we need to sort []KeyRange
type KeyRangeArray []KeyRange
func (p KeyRangeArray) Len() int { return len(p) }
func (p KeyRangeArray) Less(i, j int) bool {
return p[i].Start < p[j].Start
}
func (p KeyRangeArray) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
func (p KeyRangeArray) Sort() { sort.Sort(p) }
// ParseShardingSpec parses a string that describes a sharding
// specification. a-b-c-d will be parsed as a-b, b-c, c-d. The empty
// string may serve both as the start and end of the keyspace: -a-b-
// will be parsed as start-a, a-b, b-end.
func ParseShardingSpec(spec string) ([]*pb.KeyRange, error) {
parts := strings.Split(spec, "-")
if len(parts) == 1 {
return nil, fmt.Errorf("malformed spec: doesn't define a range: %q", spec)
}
old := parts[0]
ranges := make([]*pb.KeyRange, len(parts)-1)
for i, p := range parts[1:] {
if p == "" && i != (len(parts)-2) {
return nil, fmt.Errorf("malformed spec: MinKey/MaxKey cannot be in the middle of the spec: %q", spec)
}
if p != "" && p <= old {
return nil, fmt.Errorf("malformed spec: shard limits should be in order: %q", spec)
}
s, err := hex.DecodeString(old)
if err != nil {
return nil, err
}
if len(s) == 0 {
s = nil
}
e, err := hex.DecodeString(p)
if err != nil {
return nil, err
}
if len(e) == 0 {
e = nil
}
ranges[i] = &pb.KeyRange{Start: s, End: e}
old = p
}
return ranges, nil
}