Skip to content

Fix streaming Reader race condition #55

New issue

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

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

Already on GitHub? # to your account

Merged
merged 2 commits into from
Apr 12, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions streaming/reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ type (
bufferSize int
// channels to send notifications
chans []chan *Event
// startOnce is used to ensure the reader is started only once.
startOnce sync.Once
// donechan is the reader donechan channel.
donechan chan struct{}
// streamschan notifies the reader when streams are added or
Expand Down Expand Up @@ -114,9 +116,6 @@ func newReader(stream *Stream, opts ...options.Reader) (*Reader, error) {
rdb: stream.rdb,
}

reader.wait.Add(1)
pulse.Go(reader.logger, reader.read)

return reader, nil
}

Expand All @@ -127,6 +126,7 @@ func (r *Reader) Subscribe() <-chan *Event {
r.lock.Lock()
defer r.lock.Unlock()
r.chans = append(r.chans, c)
r.start()
return c
}

Expand Down Expand Up @@ -209,6 +209,14 @@ func (r *Reader) IsClosed() bool {
return r.closed
}

// start starts the reader's read goroutine if it is not already running.
func (r *Reader) start() {
r.startOnce.Do(func() {
r.wait.Add(1)
pulse.Go(r.logger, r.read)
})
}

// read reads events from the streams and sends them to the reader channel.
func (r *Reader) read() {
ctx := context.Background()
Expand Down