-
Notifications
You must be signed in to change notification settings - Fork 0
/
incrementer.go
63 lines (49 loc) · 1.26 KB
/
incrementer.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
package etcd
import (
"context"
"fmt"
"github.com/Focinfi/gosqs/errors"
"github.com/Focinfi/gosqs/util/strconvutil"
"github.com/coreos/etcd/clientv3"
)
// Incrementer implements the models.Incrementer
type Incrementer struct {
kv *KV
}
// Increment try to increment the value of the key
func (inc *Incrementer) Increment(key string, size int) (int64, error) {
curIDVal, getErr := inc.kv.Get(key)
// try set the value to size
if getErr == errors.DataNotFound {
maxIDVal := fmt.Sprintf("%d", size)
_, err := inc.kv.db.Txn(context.TODO()).
If(clientv3.CreateRevision(key)).
Then(clientv3.OpPut(key, maxIDVal)).
Commit()
if err != nil {
return -1, err
}
return int64(size), nil
}
if getErr != nil {
return -1, getErr
}
curID, getErr := strconvutil.ParseInt64(curIDVal)
if getErr != nil {
return -1, errors.DataBroken(key, getErr)
}
maxID := curID + int64(size)
maxIDVal := fmt.Sprintf("%d", maxID)
_, getErr = inc.kv.db.Txn(context.TODO()).
If(clientv3.Compare(clientv3.Value(key), "=", curIDVal)).
Then(clientv3.OpPut(key, maxIDVal)).
Commit()
if getErr != nil {
return -1, getErr
}
return maxID, nil
}
// NewIncrementer returns a new Incrementer
func NewIncrementer(kv *KV) *Incrementer {
return &Incrementer{kv: kv}
}