Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

fix: Broadcast of post to sse blocks execution #11

Merged
merged 1 commit into from
Nov 9, 2023
Merged
Show file tree
Hide file tree
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
5 changes: 4 additions & 1 deletion cmd/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ func serveCmd() *cli.Command {
Value: 3000,
},
},

Action: func(ctx *cli.Context) error {

log.Info("Starting Norsky feed generator")
Expand Down Expand Up @@ -100,9 +101,11 @@ func serveCmd() *cli.Command {
go func() {
for post := range postChan {
switch post := post.(type) {
// Don't crash if broadcast fails
case models.CreatePostEvent:
dbPostChan <- post
broadcaster.Broadcast(post) // Broadcast new post to SSE clients
// Broadcast without blocking
go broadcaster.Broadcast(post) // Broadcast new post to SSE clients
default:
dbPostChan <- post
}
Expand Down
9 changes: 5 additions & 4 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,6 @@ func (b *Broadcaster) Broadcast(post models.CreatePostEvent) {
log.WithFields(log.Fields{
"clients": len(b.clients),
}).Info("Broadcasting post to SSE clients")

b.Lock()
defer b.Unlock()
for _, client := range b.clients {
client <- post
}
Expand All @@ -82,8 +79,12 @@ func (b *Broadcaster) AddClient(key string, client chan models.CreatePostEvent)
func (b *Broadcaster) RemoveClient(key string) {
b.Lock()
defer b.Unlock()
// Check if client channel exists in map
if _, ok := b.clients[key]; !ok {
close(b.clients[key])
// Close the channel unless it's already closed
if b.clients[key] != nil {
close(b.clients[key])
}
delete(b.clients, key)
}

Expand Down