id.go 840 B

12345678910111213141516171819202122232425262728293031323334
  1. package alert
  2. import (
  3. "crypto/rand"
  4. "encoding/hex"
  5. "sync/atomic"
  6. "time"
  7. )
  8. // ulidLike returns a 26-char time-sortable ID. Layout:
  9. // - first 10 hex chars: unix ms (fits in 40 bits, padded)
  10. // - next 16 hex chars: random
  11. // Not a real ULID, but good enough for log ordering and broker keys.
  12. func ulidLike() string {
  13. now := time.Now().UTC().UnixMilli()
  14. var msBuf [8]byte
  15. for i := 7; i >= 0; i-- {
  16. msBuf[i] = byte(now)
  17. now >>= 8
  18. }
  19. var rnd [8]byte
  20. if _, err := rand.Read(rnd[:]); err != nil {
  21. // crypto/rand should never fail; if it does, fall back to atomic counter
  22. // so we still produce a unique ID.
  23. fb := atomic.AddUint64(&fallbackCounter, 1)
  24. for i := 7; i >= 0; i-- {
  25. rnd[i] = byte(fb)
  26. fb >>= 8
  27. }
  28. }
  29. return hex.EncodeToString(msBuf[:])[:10] + hex.EncodeToString(rnd[:])
  30. }
  31. var fallbackCounter uint64