id.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Package idutil implements utility functions for generating unique,
  15. // randomized ids.
  16. package idutil
  17. import (
  18. "math"
  19. "sync"
  20. "time"
  21. )
  22. const (
  23. tsLen = 5 * 8
  24. cntLen = 8
  25. suffixLen = tsLen + cntLen
  26. )
  27. // Generator generates unique identifiers based on counters, timestamps, and
  28. // a node member ID.
  29. //
  30. // The initial id is in this format:
  31. // High order byte is memberID, next 5 bytes are from timestamp,
  32. // and low order 2 bytes are 0s.
  33. // | prefix | suffix |
  34. // | 2 bytes | 5 bytes | 1 byte |
  35. // | memberID | timestamp | cnt |
  36. //
  37. // The timestamp 5 bytes is different when the machine is restart
  38. // after 1 ms and before 35 years.
  39. //
  40. // It increases suffix to generate the next id.
  41. // The count field may overflow to timestamp field, which is intentional.
  42. // It helps to extend the event window to 2^56. This doesn't break that
  43. // id generated after restart is unique because etcd throughput is <<
  44. // 256req/ms(250k reqs/second).
  45. type Generator struct {
  46. mu sync.Mutex
  47. // high order 2 bytes
  48. prefix uint64
  49. // low order 6 bytes
  50. suffix uint64
  51. }
  52. func NewGenerator(memberID uint16, now time.Time) *Generator {
  53. prefix := uint64(memberID) << suffixLen
  54. unixMilli := uint64(now.UnixNano()) / uint64(time.Millisecond/time.Nanosecond)
  55. suffix := lowbit(unixMilli, tsLen) << cntLen
  56. return &Generator{
  57. prefix: prefix,
  58. suffix: suffix,
  59. }
  60. }
  61. // Next generates a id that is unique.
  62. func (g *Generator) Next() uint64 {
  63. g.mu.Lock()
  64. defer g.mu.Unlock()
  65. g.suffix++
  66. id := g.prefix | lowbit(g.suffix, suffixLen)
  67. return id
  68. }
  69. func lowbit(x uint64, n uint) uint64 {
  70. return x & (math.MaxUint64 >> (64 - n))
  71. }