-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathid.go
More file actions
101 lines (84 loc) · 2.13 KB
/
id.go
File metadata and controls
101 lines (84 loc) · 2.13 KB
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
package main
import (
"errors"
"net"
"sync"
"time"
)
const (
idLen = 63 // int64
timestampLen = 39 // atm we use 38 bits (10ms) for timestamp, it tooks hundred years to get full 2^39-1
sequenceLen = 8 // per 10ms we can have most 255 id
machineIDlen = 16 // second half of ip address for host machine run this program
maskSequence = uint16(1<<sequenceLen - 1)
maskMachineID = uint64(1<<machineIDlen - 1)
maskIDSequence = uint64((1<<sequenceLen - 1) << machineIDlen)
)
type idGenerator struct {
m sync.Mutex
sequence uint8 // no needs mask
machineID uint16
}
func newIDGenerator() (*idGenerator, error) {
machineID, err := lower16BitPrivateIP()
if err != nil {
return nil, err
}
return &idGenerator{
sequence: 0,
machineID: machineID,
}, nil
}
func (i *idGenerator) next() uint64 {
i.m.Lock()
defer i.m.Unlock()
// increase the sequence
i.sequence++
// 10ms
// hopefully we won't process more than 255 image per 10ms per ip
// LOL 255/10ms = 25500/s
t := time.Now().UnixNano() / int64(10*time.Millisecond)
return uint64(t)<<(sequenceLen+machineIDlen) |
uint64(i.sequence)<<machineIDlen | uint64(i.machineID)
}
func decompose(id uint64) map[string]uint64 {
msb := id >> 63
time := id >> (sequenceLen + machineIDlen)
sequence := id & maskIDSequence >> machineIDlen
machineID := id & maskMachineID
return map[string]uint64{
"id": id,
"msb": msb,
"time": time,
"sequence": sequence,
"machine_id": machineID,
}
}
func privateIPv4() (net.IP, error) {
as, err := net.InterfaceAddrs()
if err != nil {
return nil, err
}
for _, a := range as {
ipnet, ok := a.(*net.IPNet)
if !ok || ipnet.IP.IsLoopback() {
continue
}
ip := ipnet.IP.To4()
if isPrivateIPv4(ip) {
return ip, nil
}
}
return nil, errors.New("no private ip address")
}
func isPrivateIPv4(ip net.IP) bool {
return ip != nil &&
(ip[0] == 10 || ip[0] == 172 && (ip[1] >= 16 && ip[1] < 32) || ip[0] == 192 && ip[1] == 168)
}
func lower16BitPrivateIP() (uint16, error) {
ip, err := privateIPv4()
if err != nil {
return 0, err
}
return uint16(ip[2])<<8 + uint16(ip[3]), nil
}