-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
local_version_provider.go
67 lines (55 loc) · 1.53 KB
/
local_version_provider.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
package localstore
import (
"errors"
"sync"
"time"
log "github.com/Sirupsen/logrus"
"github.com/pingcap/tidb/kv"
)
// ErrOverflow is the error returned by CurrentVersion, it describes if
// there're too many versions allocations in a very short period of time, ID
// may conflict.
var ErrOverflow = errors.New("overflow when allocating new version")
// LocalVersionProvider uses local timestamp for version.
type LocalVersionProvider struct {
mu sync.Mutex
lastTimestamp uint64
// logical guaranteed version's monotonic increasing for calls when lastTimestamp
// are equal.
logical uint64
}
const (
timePrecisionOffset = 18
)
func time2TsPhysical(t time.Time) uint64 {
return uint64((t.UnixNano() / int64(time.Millisecond)) << timePrecisionOffset)
}
func version2Second(v kv.Version) int64 {
return int64(v.Ver>>timePrecisionOffset) / 1000
}
// CurrentVersion implements the VersionProvider's GetCurrentVer interface.
func (l *LocalVersionProvider) CurrentVersion() (kv.Version, error) {
l.mu.Lock()
defer l.mu.Unlock()
for {
var ts uint64
ts = time2TsPhysical(time.Now())
if l.lastTimestamp > ts {
log.Error("[kv] invalid physical time stamp")
continue
}
if l.lastTimestamp == ts {
l.logical++
if l.logical >= 1<<timePrecisionOffset {
return kv.Version{}, ErrOverflow
}
return kv.Version{Ver: ts + l.logical}, nil
}
l.lastTimestamp = ts
l.logical = 0
return kv.Version{Ver: ts}, nil
}
}
func localVersionToTimestamp(ver kv.Version) uint64 {
return ver.Ver >> timePrecisionOffset
}