Hopefully fix a possible race condition when Unsubscribing from the EventBus while an event is being Published

This commit is contained in:
Matthew Penner 2020-07-29 23:18:11 -06:00
parent 373dbd355e
commit 5036077152
2 changed files with 23 additions and 21 deletions

View File

@ -26,9 +26,9 @@ func (h *Handler) ListenForExpiration(ctx context.Context) {
jwt := h.GetJwt() jwt := h.GetJwt()
if jwt != nil { if jwt != nil {
if jwt.ExpirationTime.Unix()-time.Now().Unix() <= 0 { if jwt.ExpirationTime.Unix()-time.Now().Unix() <= 0 {
h.SendJson(&Message{Event: TokenExpiredEvent}) _ = h.SendJson(&Message{Event: TokenExpiredEvent})
} else if jwt.ExpirationTime.Unix()-time.Now().Unix() <= 180 { } else if jwt.ExpirationTime.Unix()-time.Now().Unix() <= 180 {
h.SendJson(&Message{Event: TokenExpiringEvent}) _ = h.SendJson(&Message{Event: TokenExpiringEvent})
} }
} }
} }
@ -63,7 +63,7 @@ func (h *Handler) ListenForServerEvents(ctx context.Context) {
close(eventChannel) close(eventChannel)
default: default:
h.SendJson(&Message{ _ = h.SendJson(&Message{
Event: d.Topic, Event: d.Topic,
Args: []string{d.Data}, Args: []string{d.Data},
}) })

View File

@ -46,6 +46,7 @@ func (s *Server) Events() *EventBus {
// Publish data to a given topic. // Publish data to a given topic.
func (e *EventBus) Publish(topic string, data string) { func (e *EventBus) Publish(topic string, data string) {
go func() {
e.RLock() e.RLock()
defer e.RUnlock() defer e.RUnlock()
@ -64,12 +65,13 @@ func (e *EventBus) Publish(topic string, data string) {
} }
if ch, ok := e.subscribers[t]; ok { if ch, ok := e.subscribers[t]; ok {
go func(data Event, cs []chan Event) { data := Event{Data: data, Topic: topic}
for _, channel := range cs {
for _, channel := range ch {
channel <- data channel <- data
} }
}(Event{Data: data, Topic: topic}, ch)
} }
}()
} }
func (e *EventBus) PublishJson(topic string, data interface{}) error { func (e *EventBus) PublishJson(topic string, data interface{}) error {