-
Notifications
You must be signed in to change notification settings - Fork 11
/
id_allocator.go
48 lines (39 loc) · 1.03 KB
/
id_allocator.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
package embedshim
import (
"fmt"
"path/filepath"
bolt "go.etcd.io/bbolt"
)
var idaBucketVersion = "v1"
// idAllocator is used to generate autoincrementing integer as ID and the state
// can be persisted in disk.
type idAllocator struct {
db *bolt.DB
}
func newIDAllocator(storeDir string, dbName string) (*idAllocator, error) {
db, err := bolt.Open(filepath.Join(storeDir, dbName), 0644, nil)
if err != nil {
return nil, fmt.Errorf("failed to open db in %s: %w", storeDir, err)
}
return &idAllocator{db: db}, nil
}
func (ida *idAllocator) nextID() (uint64, error) {
var id uint64
if err := ida.db.Update(func(tx *bolt.Tx) error {
v1bkt, err := tx.CreateBucketIfNotExists([]byte(idaBucketVersion))
if err != nil {
return fmt.Errorf("failed to create version bucket: %w", err)
}
id, err = v1bkt.NextSequence()
if err != nil {
return fmt.Errorf("failed to get next ID: %w", err)
}
return nil
}); err != nil {
return 0, err
}
return id, nil
}
func (ida *idAllocator) close() error {
return ida.db.Close()
}