-
Notifications
You must be signed in to change notification settings - Fork 1
/
kv_progress_state.go
69 lines (55 loc) · 1.36 KB
/
kv_progress_state.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
package main
import (
"encoding/binary"
"fmt"
"os"
"modernc.org/kv"
)
type KVProgressState struct {
db *kv.DB
prefix string
}
func (p KVProgressState) generateKey(entityType string, entityID string) []byte {
keyName := fmt.Sprintf("%s-%s-%s", p.prefix, entityType, entityID)
return []byte(keyName)
}
func (p KVProgressState) Set(entityType string, entityID string, remoteID uint64) {
keyName := p.generateKey(entityType, entityID)
buf := make([]byte, 8)
binary.LittleEndian.PutUint64(buf, remoteID)
p.db.Set(keyName, buf)
}
func (p KVProgressState) Get(entityType string, entityID string) (remoteID uint64, found bool, err error) {
buf := make([]byte, 8)
res, err := p.db.Get(buf, p.generateKey(entityType, entityID))
if err != nil {
return 0, false, err
}
if res == nil {
return 0, false, nil
}
remoteID = binary.LittleEndian.Uint64(res)
return remoteID, true, nil
}
func (p KVProgressState) Close() error {
if p.db != nil {
return p.db.Close()
}
return nil
}
func CreateKVProgressState(prefix string, fileName string) (*KVProgressState, error) {
var db *kv.DB
var dberror error
if _, err := os.Stat(fileName); os.IsNotExist(err) {
db, dberror = kv.Create(fileName, &kv.Options{})
} else {
db, dberror = kv.Open(fileName, &kv.Options{})
}
if dberror != nil {
return nil, dberror
}
return &KVProgressState{
db,
prefix,
}, nil
}