-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement pubsub broker to broadcast lines to all websocket clients
fixes case where new websocket clients consume lines, resulting in incomplete logs in all websocket clients
- Loading branch information
Showing
4 changed files
with
94 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
// Sourced from https://github.com/eliben/code-for-blog/blob/master/2020/go-pubsub/pubsub-channel-return.go | ||
// and https://eli.thegreenplace.net/2020/pubsub-using-channels-in-go/ | ||
// License; Public Domain | ||
|
||
package internal | ||
|
||
import ( | ||
"sync" | ||
) | ||
|
||
type Pubsub struct { | ||
mu sync.RWMutex | ||
subs map[string][]chan string | ||
closed bool | ||
} | ||
|
||
func NewPubsub() *Pubsub { | ||
ps := &Pubsub{} | ||
ps.subs = make(map[string][]chan string) | ||
ps.closed = false | ||
return ps | ||
} | ||
|
||
func (ps *Pubsub) Subscribe(topic string) <-chan string { | ||
ps.mu.Lock() | ||
defer ps.mu.Unlock() | ||
|
||
ch := make(chan string, 1) | ||
ps.subs[topic] = append(ps.subs[topic], ch) | ||
return ch | ||
} | ||
|
||
func (ps *Pubsub) Publish(topic string, msg string) { | ||
ps.mu.RLock() | ||
defer ps.mu.RUnlock() | ||
|
||
if ps.closed { | ||
return | ||
} | ||
|
||
for _, ch := range ps.subs[topic] { | ||
ch <- msg | ||
} | ||
} | ||
|
||
func (ps *Pubsub) Close() { | ||
ps.mu.Lock() | ||
defer ps.mu.Unlock() | ||
|
||
if !ps.closed { | ||
ps.closed = true | ||
for _, subs := range ps.subs { | ||
for _, ch := range subs { | ||
close(ch) | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters