File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -18,6 +18,8 @@ const (
1818 MAX12BITS = 4095
1919 // MAX41BITS is the maximum value for a 41 bits number
2020 MAX41BITS = 2199023255551
21+ // CLOCK_DRIFT_TOLERANCE_MS is the tolerance for clock drift in milliseconds
22+ CLOCK_DRIFT_TOLERANCE_MS = 10
2123)
2224
2325// Spaceflake represents a Spaceflake
@@ -199,11 +201,12 @@ func (w *Worker) GenerateSpaceflake() (*Spaceflake, error) {
199201 milliseconds := uint64 (math .Floor (microTime () * 1000 ))
200202 milliseconds -= w .BaseEpoch
201203
202- if milliseconds < w .lastTimestamp {
203- for milliseconds < w .lastTimestamp {
204- time .Sleep (time .Millisecond )
205- milliseconds = uint64 (math .Floor (microTime ()* 1000 )) - w .BaseEpoch
204+ if delta := w .lastTimestamp - milliseconds ; milliseconds < w .lastTimestamp {
205+ if delta >= CLOCK_DRIFT_TOLERANCE_MS {
206+ return nil , fmt .Errorf ("clock moved backwards by %dms" , delta )
206207 }
208+ time .Sleep (time .Duration (delta + 1 ) * time .Millisecond )
209+ milliseconds = uint64 (math .Floor (microTime ()* 100 )) - w .BaseEpoch
207210 }
208211
209212 w .lastTimestamp = milliseconds
You can’t perform that action at this time.
0 commit comments