Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix possibility to generate duplicate IDs in XADD #275

Merged
merged 1 commit into from Jun 29, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 15 additions & 8 deletions stream.go
Expand Up @@ -14,8 +14,9 @@ import (

// a Stream is a list of entries, lowest ID (oldest) first, and all "groups".
type streamKey struct {
entries []StreamEntry
groups map[string]*streamGroup
entries []StreamEntry
groups map[string]*streamGroup
lastAllocatedID string
}

// a StreamEntry is an entry in a stream. The ID is always of the form
Expand Down Expand Up @@ -53,14 +54,20 @@ func newStreamKey() *streamKey {
func (s *streamKey) generateID(now time.Time) string {
ts := uint64(now.UnixNano()) / 1_000_000

lastID := s.lastID()

next := fmt.Sprintf("%d-%d", ts, 0)
if streamCmp(lastID, next) == -1 {
return next
if s.lastAllocatedID != "" && streamCmp(s.lastAllocatedID, next) >= 0 {
last, _ := parseStreamID(s.lastAllocatedID)
next = fmt.Sprintf("%d-%d", last[0], last[1]+1)
}

lastID := s.lastID()
if streamCmp(lastID, next) >= 0 {
last, _ := parseStreamID(lastID)
next = fmt.Sprintf("%d-%d", last[0], last[1]+1)
}
last, _ := parseStreamID(lastID)
return fmt.Sprintf("%d-%d", last[0], last[1]+1)

s.lastAllocatedID = next
return next
}

func (s *streamKey) lastID() string {
Expand Down