sony / sonyflake

A distributed unique ID generator inspired by Twitter's Snowflake
MIT License
3.89k stars 304 forks source link

sonyflake not created[ ErrNoPrivateAddress Error in Docker or Environments Without Private IPv4] #57

Closed NidhoogJX closed 2 months ago

NidhoogJX commented 2 months ago

When running in Docker or similar environments without a private IPv4 address, the error ErrNoPrivateAddress = errors.New("no private IP address") is generated. However, the NewSonyflake method does not return this error, so you only get a nil value.

var st sonyflake.Settings
st.StartTime = time.Date(2024, 4, 21, 0, 0, 0, 0, time.UTC)
log.Info("init sonyflakeHandle%v", st)
flake = sonyflake.NewSonyflake(st)
if flake == nil {
    log.Fatalln("sonyflake not created")
}

When generating an ID, it will prompt "sonyflake not created" but will not tell you why it failed to create. I even thought it was due to cross-compilation incompatibility with the amd64 architecture. However, after reviewing the source code, I found that no error is returned, which is not a good practice. The caller should know what happened or be provided with a solution.

For example, adding an IP field to the Settings struct would allow the code to run correctly even in environments without a private IP address. id, err := flake.NextID()

if err != nil {
    return "", err
}

This issue highlights the need for better error handling and configuration options in the NewSonyflake method to support environments without private IPv4 addresses.

old

// NewSonyflake returns a new Sonyflake configured with the given Settings. // NewSonyflake returns nil in the following cases: // - Settings.StartTime is ahead of the current time. // - Settings.MachineID returns an error. // - Settings.CheckMachineID returns false. func NewSonyflake(st Settings) *Sonyflake { sf, _ := New(st) return sf }

new

// NewSonyflake returns a new Sonyflake configured with the given Settings. // NewSonyflake returns nil in the following cases: // - Settings.StartTime is ahead of the current time. // - Settings.MachineID returns an error. // - Settings.CheckMachineID returns false. // Note: This function does not support running in environments without a private IP address. // As an alternative, you can add an IP field to the Settings struct to specify an IP address manually.

func NewSonyflake(st Settings) (*Sonyflake,error) {
sf, err := New(st)
if err != nil {
fmt.Println(err.Error())
}
return sf,err
}