Fix MessageChannel leaks (#646)

This commit is contained in:
David Zhao
2022-04-22 10:53:20 -07:00
committed by GitHub
parent 2e182afb61
commit b7d22c4f34
8 changed files with 161 additions and 117 deletions
+18 -15
View File
@@ -1,22 +1,24 @@
package routing
import (
"sync"
"google.golang.org/protobuf/proto"
)
const DefaultMessageChannelSize = 200
type MessageChannel struct {
msgChan chan proto.Message
closed chan struct{}
onClose func()
msgChan chan proto.Message
onClose func()
isClosed bool
lock sync.RWMutex
}
func NewMessageChannel(size int) *MessageChannel {
return &MessageChannel{
// allow some buffer to avoid blocked writes
msgChan: make(chan proto.Message, size),
closed: make(chan struct{}),
}
}
@@ -25,22 +27,19 @@ func (m *MessageChannel) OnClose(f func()) {
}
func (m *MessageChannel) IsClosed() bool {
select {
case <-m.closed:
return true
default:
return false
}
m.lock.RLock()
defer m.lock.RUnlock()
return m.isClosed
}
func (m *MessageChannel) WriteMessage(msg proto.Message) error {
if m.IsClosed() {
m.lock.RLock()
defer m.lock.RUnlock()
if m.isClosed {
return ErrChannelClosed
}
select {
case <-m.closed:
return ErrChannelClosed
case m.msgChan <- msg:
// published
return nil
@@ -55,11 +54,15 @@ func (m *MessageChannel) ReadChan() <-chan proto.Message {
}
func (m *MessageChannel) Close() {
if m.IsClosed() {
m.lock.Lock()
if m.isClosed {
m.lock.Unlock()
return
}
close(m.closed)
m.isClosed = true
close(m.msgChan)
m.lock.Unlock()
if m.onClose != nil {
m.onClose()
}