Debian Codegraph @

snowflake.go

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // Package snowflake is a network service for generating unique ID numbers at high scale with some simple guarantees.
2 // The first bit is unused sign bit.
3 // The second part consists of a 41-bit timestamp (milliseconds) whose value is the offset of the current time relative to a certain time.
4 // The 6 bits machineID, max num is 2^4 = 32.
5 // The last part consists of 6 bits, its means the length of the serial number generated per millisecond per working node, a maximum of 2^6 = 64 IDs can be generated in the same millisecond.
6 // The binary length of 41 bits is at most 2^41 millisecond = 69 years. So the snowflake algorithm can be used for up to 69 years, In order to maximize the use of the algorithm, you should specify a start time for it.
7 package snowflake
8
9 import (
10 "errors"
11 "fmt"
12 "time"
13 )
14
15 // These constants are the bit lengths of snowflake ID parts.
16 const (
17 TimestampLength = 41
18 MachineIDLength = 6
19 SequenceLength = 6
20
21 MaxTimestamp = 1<<TimestampLength - 1
22 MaxMachineID = 1<<MachineIDLength - 1
23 MaxSequence = 1<<SequenceLength - 1
24
25 machineIDMoveLength = SequenceLength
26 timestampMoveLength = MachineIDLength + SequenceLength
27 )
28
29 // SequenceResolver the snowflake sequence resolver.
30 //
31 // When you want use the snowflake algorithm to generate unique ID, You must ensure: The sequence-number generated in the same millisecond of the same node is unique.
32 // Based on this, we create this interface provide following reslover:
33 //
34 // AtomicResolver : base sync/atomic (by default).
35 type SequenceResolver func(ms int64) (uint16, error)
36
37 // default machineID is 0
38 // default resolver is AtomicResolver
39 // default startTime is 2020-01-01 00:00:00 UTC
40 var (
41 resolver SequenceResolver
42 machineID = 0
43 startTime = time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)
44 )
45
46 // ID use ID to generate snowflake id and it will ignore error. if you want error info, you need use NextID method.
47 // This function is thread safe.
48 func ID() uint64 {
49 id, _ := NextID()
50 return id
51 }
52
53 // NextID use NextID to generate snowflake id and return an error.
54 // This function is thread safe.
55 func NextID() (uint64, error) {
56 c := currentMillis()
57 seqResolver := callSequenceResolver()
58 seq, err := seqResolver(c)
59
60 if err != nil {
61 return 0, err
62 }
63
64 for seq >= MaxSequence {
65 c = waitForNextMillis(c)
66 seq, err = seqResolver(c)
67 if err != nil {
68 return 0, err
69 }
70 }
71
72 df := int(elapsedTime(c, startTime))
73 if df < 0 || df > MaxTimestamp {
74 return 0, errors.New("The maximum life cycle of the snowflake algorithm is 2^41(millis), please check starttime")
75 }
76
77 id := uint64((df << timestampMoveLength) | (machineID << machineIDMoveLength) | int(seq))
78 return id, nil
79 }
80
81 // SetStartTime set the start time for snowflake algorithm.
82 //
83 // It will panic when:
84 //
85 // s IsZero
86 // s > current millisecond
87 // current millisecond - s > 2^41(69 years).
88 //
89 // This function is thread-unsafe, recommended you call him in the main function.
90 func SetStartTime(s time.Time) {
91 s = s.UTC()
92
93 if s.IsZero() {
94 panic("The start time cannot be a zero value")
95 }
96
97 if s.After(time.Now().UTC()) {
98 panic("The s cannot be greater than the current millisecond")
99 }
100
101 // Because s must after now, so the `df` not < 0.
102 df := elapsedTime(currentMillis(), s)
103 if df > MaxTimestamp {
104 panic("The maximum life cycle of the snowflake algorithm is 69 years")
105 }
106
107 startTime = s
108 }
109
110 // SetMachineID specify the machine ID. It will panic when machineid > max limit for 2^6-1=63.
111 // This function is thread-unsafe, recommended you call him in the main function.
112 func SetMachineID(m int) {
113 if m > MaxMachineID {
114 panic(fmt.Sprintf("The machineid cannot be greater than %d", MaxMachineID))
115 }
116 machineID = m
117 }
118
119 // SetSequenceResolver set an custom sequence resolver.
120 // This function is thread-unsafe, recommended you call him in the main function.
121 func SetSequenceResolver(seq SequenceResolver) {
122 if seq != nil {
123 resolver = seq
124 }
125 }
126
127 // SID snowflake id
128 type SID struct {
129 Sequence uint64
130 MachineID uint64
131 Timestamp uint64
132 ID uint64
133 }
134
135 // GenerateTime snowflake generate at, return a UTC time.
136 func (id *SID) GenerateTime() time.Time {
137 ms := startTime.UTC().UnixNano()/1e6 + int64(id.Timestamp)
138
139 return time.Unix(0, ms*int64(time.Millisecond)).UTC()
140 }
141
142 // ParseID parse snowflake it to SID struct.
143 func ParseID(id uint64) SID {
144 time := id >> (SequenceLength + MachineIDLength)
145 sequence := id & MaxSequence
146 machineID := (id & (MaxMachineID << SequenceLength)) >> SequenceLength
147
148 return SID{
149 ID: id,
150 Sequence: sequence,
151 MachineID: machineID,
152 Timestamp: time,
153 }
154 }
155
156 //--------------------------------------------------------------------
157 // private function defined.
158 //--------------------------------------------------------------------
159
160 func waitForNextMillis(last int64) int64 {
161 now := currentMillis()
162 for now == last {
163 now = currentMillis()
164 }
165 return now
166 }
167
168 func callSequenceResolver() SequenceResolver {
169 if resolver == nil {
170 return AtomicResolver
171 }
172
173 return resolver
174 }
175
176 func elapsedTime(nowms int64, s time.Time) int64 {
177 return nowms - s.UTC().UnixNano()/1e6
178 }
179
180 // currentMillis get current millisecond.
181 func currentMillis() int64 {
182 return time.Now().UTC().UnixNano() / 1e6
183 }