Permalink
Browse files

moving time inequality to prevent duplicate id on backwards time

If time moves backwards so that ts is before lts, the ts/lts equality check
fails and the sequence number is set to 0. If time moves back to the correct
millisecond on the next request, the sequence number at 0 is used, instead of
whatever sequence number it was previously on.

By moving the going-backwards-time check before the inequality, we avoid this.
  • Loading branch information...
1 parent ff2c4d3 commit 195465a33e1feaab36b5e5d089892a0adc60c0b6 @jmhodges jmhodges committed Apr 7, 2012
Showing with 5 additions and 4 deletions.
  1. +5 −4 main.go
View
@@ -148,6 +148,11 @@ func nextId() (int64, error) {
defer mu.Unlock()
ts := milliseconds()
+
+ if ts < *lts {
+ return 0, fmt.Errorf("time is moving backwards, waiting until %d\n", *lts)
+ }
+
if *lts == ts {
seq = (seq + 1) & sequenceMask
if seq == 0 {
@@ -159,10 +164,6 @@ func nextId() (int64, error) {
seq = 0
}
- if ts < *lts {
- return 0, fmt.Errorf("time is moving backwards, waiting until %d\n", *lts)
- }
-
*lts = ts
id := ((ts - twepoch) << timestampLeftShift) |

0 comments on commit 195465a

Please sign in to comment.