return error when uuid is not enough

This commit is contained in:
MaysWind
2023-09-16 22:31:20 +08:00
parent 729904e1c3
commit 165377816c
10 changed files with 94 additions and 3 deletions
+11
View File
@@ -51,6 +51,11 @@ func NewInternalUuidGenerator(config *settings.Config) (*InternalUuidGenerator,
// GenerateUuid generates a new uuid
func (u *InternalUuidGenerator) GenerateUuid(idType UuidType) int64 {
uuids := u.GenerateUuids(idType, 1)
if len(uuids) < 1 {
return 0
}
return uuids[0]
}
@@ -89,6 +94,12 @@ func (u *InternalUuidGenerator) GenerateUuids(idType UuidType, count uint8) []in
for i := 0; i < int(count); i++ {
seqId := (newFirstSeqId + uint64(i)) & seqNumberIdMask
// the internal uuid generator can only generate 524,287 ids per second for specified type
if seqId > internalUuidSeqIdMask {
return nil
}
uuids[i] = u.assembleUuid(unixTime, uuidType, seqId)
}
+22
View File
@@ -374,3 +374,25 @@ func TestGenerateUuids_1000000TimesConcurrent(t *testing.T) {
waitGroup.Wait()
}
func TestGenerateUuid_Over524287Times(t *testing.T) {
generator, _ := NewInternalUuidGenerator(&settings.Config{UuidServerId: 1})
onceGenerateCount := uint8(255)
generationStartUnixTime := time.Now().Unix()
for i := 0; i < 2057; i++ { // 2056*255=524280, 2057*255=524,535 (only can generates 524,287 uuids per second)
uuids := generator.GenerateUuids(UUID_TYPE_USER, onceGenerateCount)
if i < 2056 {
if len(uuids) < int(onceGenerateCount) {
assert.Fail(t, fmt.Sprintf("%d uuids should be generated", onceGenerateCount))
}
} else {
generationEndUnixTime := time.Now().Unix()
if generationStartUnixTime == generationEndUnixTime && len(uuids) > 0 {
assert.Fail(t, fmt.Sprintf("uuids should not be generated because there are too many uuids in one second"))
}
}
}
}