-
Notifications
You must be signed in to change notification settings - Fork 0
/
monoflake.go
165 lines (134 loc) · 4.3 KB
/
monoflake.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
// Copyright 2024 Mustafa Turan. All rights reserved.
// Use of this source code is governed by a Apache License 2.0 license that can
// be found in the LICENSE file.
/*
Package monoflake is a highly scalable, single/multi node, human-readable,
predictable and incremental 64 bits (8bytes) unique id generator
# Time ordered
The `monoflake` package provides sequences based on the `monotonic` time which
represents the absolute elapsed wall-clock time since some arbitrary, fixed
point in the pasmf. It isn't affected by changes in the system time-of-day clock.
# Epoch time
Epoch time value opens space for time value by subtracting the given value from the time sequence.
# Readable
It comes with `String()` method which encodes the ids into base62 as string and allows padded with zeros to 11 bytes.
# Ready to use bytes
`Bytes()` method allows converting the id directly into static 11 bytes.
# Multi Node Support
The `monoflake` package can be used on single/multiple nodes without the need for
machine coordination. It uses configured node identifier to generate ids by
attaching the node identifier to the end of the sequences.
# Zero allocation
Zero allocation magic with blazing fast results.
*/
package monoflake
import (
"sync"
"time"
)
type (
MonoFlake struct {
nodeID int64
maxSequence int64
epoch time.Time
millisec int64
sequence int64
nodeBits int64
mu *sync.Mutex
}
err string
Option func(*MonoFlake) error
)
func (e err) Error() string {
return string(e)
}
const (
ErrEpochTooEarly err = "epoch is too earlier than June 1st 2024 UTC"
ErrNodeBitsLowerThanMin err = "node bits must be greater than 8"
ErrNodeBitsGreaterThanMax err = "node bits must be less than 13"
minEpoch int64 = 1717200000 // June 1st 2024 UTC
minSequenceBits int64 = 10 // min 1024
minNodeBits int64 = 8 // min 256
totalBits int64 = 64
reservedSignBits int64 = 1
reservedEpochBits int64 = 40 // 40 bits for milliseconds since epoch
reservedAllocationBits int64 = totalBits - reservedSignBits - reservedEpochBits
defaultReservedNodeBits int64 = 10
defaultReservedSequenceBits int64 = reservedAllocationBits - defaultReservedNodeBits
defaultMaxSequence int64 = 2 << (defaultReservedSequenceBits - 1)
)
// WithMaxSequenceBits sets the maximum number of bits for node identifier and reserves the rest for sequence number
func WithNodeBits(bits int) Option {
nodeBits := int64(bits)
return func(mf *MonoFlake) error {
if nodeBits < minNodeBits {
return ErrNodeBitsLowerThanMin
}
if nodeBits > reservedAllocationBits-minSequenceBits {
return ErrNodeBitsGreaterThanMax
}
mf.nodeBits = nodeBits
mf.maxSequence = 2 << (reservedAllocationBits - nodeBits - 1)
return nil
}
}
// WithEpoch sets the epoch time for the generator
func WithEpoch(epoch time.Time) Option {
return func(mf *MonoFlake) error {
if epoch.Unix() < minEpoch {
return ErrEpochTooEarly
}
mf.epoch = epoch
return nil
}
}
// WithNodeID sets the node identifier for the generator
func withNodeID(nodeID int64) Option {
return func(mf *MonoFlake) error {
mf.nodeID = nodeID % (2 << (mf.nodeBits - 1))
return nil
}
}
/*
Default setup:
| 1 bit (reserved) | 40 bits (since epoch) | 13 bits (sequencer) | 10 bits (node id) |
| 0 | [0, 1099511627776) | [0-8192) | [0, 1024) |
*/
// New creates a new MonoFlake generator
func New(nodeID uint16, opts ...Option) (*MonoFlake, error) {
epoch := time.Unix(minEpoch, 0)
mf := MonoFlake{
epoch: epoch,
maxSequence: defaultMaxSequence,
nodeBits: defaultReservedNodeBits,
mu: &sync.Mutex{},
}
opts = append(opts, withNodeID(int64(nodeID)))
for _, opt := range opts {
if err := opt(&mf); err != nil {
return nil, err
}
}
return &mf, nil
}
// Next generates a new unique int64 ID
func (mf *MonoFlake) Next() ID {
mf.mu.Lock()
defer mf.mu.Unlock()
seq, ms := mf.sequence, mf.millisec
since := time.Since(mf.epoch).Milliseconds()
if since < ms {
since = ms
} else if since > ms {
seq = 0
}
nextMs := since
nextSeq := seq + 1
if nextSeq >= mf.maxSequence {
nextSeq = 0
nextMs++
}
mf.millisec = nextMs
mf.sequence = nextSeq
return ID(since<<reservedAllocationBits | seq<<mf.nodeBits | mf.nodeID)
}