bwmarrin / snowflake

A simple to use Go (golang) package to generate or parse Twitter snowflake IDs
BSD 2-Clause "Simplified" License
3.02k stars 374 forks source link

Check for backwards time #14

Closed whwright closed 6 years ago

whwright commented 6 years ago

Issue: https://github.com/bwmarrin/snowflake/issues/11

I opted to create a new API that will return an error. This maintains backwards compatibility with the current API, but provides future ability to implement different error cases. It also returns a specific error type that allows the caller to do what they wish with the clock drift (wait, blow up, etc).

Let me know what you think!

Here is an example I used ```go package main import ( "fmt" "time" "github.com/whwright/snowflake" ) func main() { fmt.Println("Hello, World") node, err := snowflake.NewNode(1) if err != nil { fmt.Println("Failed to create note: %v", err) return } for { id, err := node.GenerateID() if err != nil { if bterr, ok := err.(snowflake.BackwardsTimeError); ok { fmt.Println("backwards time!") fmt.Println("try again in ", bterr.Offset()) } else { // this will never happen with current implementation, but it's here just in case fmt.Println("other err") fmt.Println(err) } return } fmt.Println(id) time.Sleep(time.Second * 1) } } ```


I ran this, and then manually set the clock backwards:

``` Hello, World 984474352814657536 984474357008961536 984474361207459840 984474365401763840 backwards time! try again in 153463 ```