Skip to content

Commit f3ff91a

Browse files
authored
Merge pull request #303 from alicebob/fixrace
fix a race in the stream code
2 parents 1bcf722 + 08c2456 commit f3ff91a

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

stream.go

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ func (s *streamKey) generateID(now time.Time) string {
6464
next = fmt.Sprintf("%d-%d", last[0], last[1]+1)
6565
}
6666

67-
lastID := s.lastID()
67+
lastID := s.lastIDUnlocked()
6868
if streamCmp(lastID, next) >= 0 {
6969
last, _ := parseStreamID(lastID)
7070
next = fmt.Sprintf("%d-%d", last[0], last[1]+1)
@@ -74,8 +74,16 @@ func (s *streamKey) generateID(now time.Time) string {
7474
return next
7575
}
7676

77-
// lastID doesn't lock the mutex
77+
// lastID locks the mutex
7878
func (s *streamKey) lastID() string {
79+
s.mu.Lock()
80+
defer s.mu.Unlock()
81+
82+
return s.lastIDUnlocked()
83+
}
84+
85+
// lastID doesn't lock the mutex
86+
func (s *streamKey) lastIDUnlocked() string {
7987
if len(s.entries) == 0 {
8088
return "0-0"
8189
}
@@ -209,7 +217,7 @@ func (s *streamKey) createGroup(group, id string) error {
209217
}
210218

211219
if id == "$" {
212-
id = s.lastID()
220+
id = s.lastIDUnlocked()
213221
}
214222
s.groups[group] = &streamGroup{
215223
stream: s,
@@ -237,7 +245,7 @@ func (s *streamKey) add(entryID string, values []string, now time.Time) (string,
237245
if entryID == "0-0" {
238246
return "", errors.New(msgStreamIDZero)
239247
}
240-
if streamCmp(s.lastID(), entryID) != -1 {
248+
if streamCmp(s.lastIDUnlocked(), entryID) != -1 {
241249
return "", errors.New(msgStreamIDTooSmall)
242250
}
243251

0 commit comments

Comments
 (0)