-
Notifications
You must be signed in to change notification settings - Fork 2
/
unique_id.go
288 lines (237 loc) · 7.36 KB
/
unique_id.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
package cypress
import (
"context"
"encoding/binary"
"errors"
"reflect"
"sync"
"sync/atomic"
"go.uber.org/zap"
)
const (
// PartitionKeyBitWidth bits for partition value
PartitionKeyBitWidth = 5
// PartitionKeyMask partition value mask
PartitionKeyMask = 0x1f
// SegmentedIDBitWidth segmented id value bit width
SegmentedIDBitWidth = 7
// SegmentedIDMask segmented id value mask
SegmentedIDMask = 0x7f
// PooledIDBitWidth pooled id value bit width
PooledIDBitWidth = PartitionKeyBitWidth + SegmentedIDBitWidth
// MaxPooledID maximum pooled id
MaxPooledID = (int64(1) << (64 - PooledIDBitWidth)) - 1
// MaxSegmentedID max segmented id
MaxSegmentedID = int64(1 << SegmentedIDBitWidth)
)
var (
// ErrOutOfRange value out of range
ErrOutOfRange = errors.New("value out of range")
)
// PartitionCalculator partition key calculator
type PartitionCalculator interface {
GetPartition(key string) int32
}
// UniqueID global unique id for a given namespace in cluster
type UniqueID struct {
Value int64 // format [PooledID][Partition][SegmentedID]
}
// Partition gets the partition for the unique id
func (id UniqueID) Partition() int32 {
return GetPartitionKey(id.Value)
}
// NewUniqueID create a new unique id based on the pooledID, partition and segmentedID
func NewUniqueID(pooledID int64, partition int32, segmentedID int32) (UniqueID, error) {
if pooledID > MaxPooledID || partition > PartitionKeyMask || segmentedID > SegmentedIDMask {
return UniqueID{0}, ErrOutOfRange
}
return UniqueID{(pooledID << PooledIDBitWidth) | int64((partition<<SegmentedIDBitWidth)|segmentedID)}, nil
}
// GetPartitionKey gets the partition key from the given unique ID value
func GetPartitionKey(id int64) int32 {
return int32((id >> SegmentedIDBitWidth) & PartitionKeyMask)
}
// PartitionCalculateFunc partition calculate function, implements PartitionCalculator
type PartitionCalculateFunc func(key string) int32
// GetPartition implements PartitionCalculator
func (calc PartitionCalculateFunc) GetPartition(key string) int32 {
return calc(key)
}
// CalculateMd5PartitionKey Md5 based partition key calculator
func CalculateMd5PartitionKey(key string) int32 {
data := Md5([]byte(key))
id := binary.BigEndian.Uint64(data[0:8])
return int32(id % PartitionKeyMask)
}
// CalculateMd5PartitionKey2 Md5 based partition key calculator, a fixed version to CalculateMd5PartitionKey
func CalculateMd5PartitionKey2(key string) int32 {
data := Md5([]byte(key))
id := binary.LittleEndian.Uint64(data[0:8])
return int32(id % (1 << PartitionKeyBitWidth))
}
// UniqueIDPool unique id pool
type UniqueIDPool struct {
pooledIDs []int64
partitionLocks []*sync.Mutex
Lock *sync.Mutex
}
// NewUniqueIDPool creates a new ID pool
func NewUniqueIDPool() *UniqueIDPool {
pooledIDs := make([]int64, PartitionKeyMask+1)
partitionLocks := make([]*sync.Mutex, 1<<PartitionKeyBitWidth)
for i := 0; i < len(pooledIDs); i = i + 1 {
pooledIDs[i] = MaxSegmentedID
}
for i := 0; i < len(partitionLocks); i = i + 1 {
partitionLocks[i] = &sync.Mutex{}
}
return &UniqueIDPool{
pooledIDs: pooledIDs,
partitionLocks: partitionLocks,
Lock: &sync.Mutex{},
}
}
// NextID generate a new id from pool
func (pool *UniqueIDPool) NextID(ctx context.Context, partition int32) (int64, error) {
if partition > PartitionKeyMask {
return 0, ErrOutOfRange
}
pool.partitionLocks[partition].Lock()
defer pool.partitionLocks[partition].Unlock()
return atomic.AddInt64(&pool.pooledIDs[partition], 1), nil
}
// UpdatePooledID update pooled id for the given partition
func (pool *UniqueIDPool) UpdatePooledID(partition int32, pooledID int64) error {
if partition > PartitionKeyMask {
return ErrOutOfRange
}
atomic.StoreInt64(&pool.pooledIDs[partition], pooledID<<PooledIDBitWidth)
return nil
}
// UniqueIDGenerator unique id generator interface
type UniqueIDGenerator interface {
NextUniqueID(ctx context.Context, name string, partition int32) (UniqueID, error)
}
// PooledID unique id pooled ID record, requires the following table
/// create table `pooled_id` (
/// `name` varchar(200) not null,
/// `partition` int not null,
/// `pooled_id` bigint not null,
/// constraint `pk_id_generator` primary key (`name`, `partition`)
/// );
type PooledID struct {
Name string `col:"name" dtags:"key,nogen"`
Partition int32 `col:"partition"`
PooledID int64 `col:"pooled_id"`
}
var pooledIDType = reflect.TypeOf((*PooledID)(nil))
// DbUniqueIDGenerator database based unique id generator
type DbUniqueIDGenerator struct {
dbAccessor *DbAccessor
pools *ConcurrentMap[string, *UniqueIDPool]
}
// implement UniqueIDGenerator
func isValidID(id int64) bool {
return (id & int64(PartitionKeyMask<<SegmentedIDBitWidth)) == 0
}
// NewDbUniqueIDGenerator creates a db based unique id generator
func NewDbUniqueIDGenerator(dbAccessor *DbAccessor) *DbUniqueIDGenerator {
return &DbUniqueIDGenerator{
dbAccessor: dbAccessor,
pools: NewConcurrentMap[string, *UniqueIDPool](),
}
}
type retryableError struct {
err error
}
func (e *retryableError) Error() string {
return e.err.Error()
}
func (e *retryableError) Unwrap() error {
return e.err
}
// NextUniqueID generate a next unique id
func (generator *DbUniqueIDGenerator) NextUniqueID(ctx context.Context, name string, partition int32) (UniqueID, error) {
var uniqueID UniqueID
err := LogOperation(ctx, "GenerateUniqueId", func() error {
pool := generator.pools.GetOrCompute(name, func() *UniqueIDPool {
return NewUniqueIDPool()
})
id, err := pool.NextID(ctx, partition)
if err != nil {
return err
}
for !isValidID(id) {
retryLeft := 3
for retryLeft > 0 {
err = func() error {
pool.Lock.Lock()
defer pool.Lock.Unlock()
id, err = pool.NextID(ctx, partition)
if isValidID(id) {
return nil
}
obj, queryErr := generator.dbAccessor.QueryOne(
ctx,
"select * from `pooled_id` where `name`=? and `partition`=?",
NewSmartMapper(pooledIDType),
name, partition)
if queryErr != nil {
return queryErr
}
if obj == nil {
_, err = generator.dbAccessor.Insert(
ctx,
&PooledID{
Name: name,
Partition: partition,
PooledID: 1,
})
if err != nil {
return &retryableError{err}
}
pool.UpdatePooledID(partition, 1)
} else {
pooledID := obj.(*PooledID)
r, err := generator.dbAccessor.Execute(
ctx,
"update `pooled_id` set `pooled_id`=`pooled_id`+1 where `name`=? and `partition`=? and `pooled_id`=?",
name,
partition,
pooledID.PooledID)
if err != nil {
return err
}
if cnt, _ := r.RowsAffected(); cnt == 0 {
return &retryableError{
err: errors.New("try to update a row that has been changed"),
}
}
pool.UpdatePooledID(partition, pooledID.PooledID+1)
}
id, err = pool.NextID(ctx, partition)
return err
}()
if err != nil {
if e, ok := err.(*retryableError); ok {
retryLeft--
if retryLeft == 0 {
err = e.Unwrap()
} else {
zap.L().Error("failed to allocate unique id", zap.Error(e.Unwrap()), zap.Int("retry", retryLeft))
continue
}
}
}
// no need to retry
break
}
if err != nil {
return err
}
}
uniqueID, err = NewUniqueID(id>>PooledIDBitWidth, partition, int32(id&SegmentedIDMask))
return err
})
return uniqueID, err
}