From 339b9cfd376ee9f07399c9e4614bc423ed3ca142 Mon Sep 17 00:00:00 2001 From: Johan Siebens Date: Sat, 23 Dec 2023 11:16:10 +0100 Subject: [PATCH] fix: lazy load snowflake id generator --- internal/util/id.go | 35 ++++++++++++++++++++++------------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/internal/util/id.go b/internal/util/id.go index a1b22d6..54e05d5 100644 --- a/internal/util/id.go +++ b/internal/util/id.go @@ -6,19 +6,33 @@ import ( "net" "os" "strconv" + "sync" "time" ) -var sf *sonyflake.Sonyflake +var ( + sf *sonyflake.Sonyflake + sfOnce sync.Once +) -func init() { - sf = sonyflake.NewSonyflake(sonyflake.Settings{ - MachineID: machineID(), - StartTime: time.Date(2022, 05, 01, 00, 0, 0, 0, time.UTC), +func NextID() uint64 { + ensureProvider() + id, _ := sf.NextID() + return id +} + +func ensureProvider() { + sfOnce.Do(func() { + sfInstance, err := sonyflake.New(sonyflake.Settings{ + MachineID: machineID(), + StartTime: time.Date(2022, 05, 01, 00, 0, 0, 0, time.UTC), + }) + if err != nil { + panic("unable to initialize sonyflake: " + err.Error()) + } + + sf = sfInstance }) - if sf == nil { - panic("unable to initialize sonyflake") - } } func machineID() func() (uint16, error) { @@ -46,8 +60,3 @@ func machineID() func() (uint16, error) { return nil } - -func NextID() uint64 { - id, _ := sf.NextID() - return id -}