Fix race conditions and shutdown behavior

Co-authored-by: blackboxprogramming <118287761+blackboxprogramming@users.noreply.github.com>
This commit is contained in:
copilot-swe-agent[bot]
2025-11-24 18:10:38 +00:00
parent 82a39701e6
commit 031e4f0cc6
2 changed files with 12 additions and 9 deletions

View File

@@ -59,7 +59,6 @@ func main() {
if err := app.Shutdown(); err != nil { if err := app.Shutdown(); err != nil {
log.Printf("error during shutdown: %v", err) log.Printf("error during shutdown: %v", err)
} }
os.Exit(0)
}() }()
if err := app.Listen(addr); err != nil { if err := app.Listen(addr); err != nil {

View File

@@ -5,6 +5,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"log" "log"
"sync"
"time" "time"
"blackroad-os-beacon/internal/model" "blackroad-os-beacon/internal/model"
@@ -14,10 +15,11 @@ import (
// StreamHub manages SSE clients. // StreamHub manages SSE clients.
type StreamHub struct { type StreamHub struct {
clients map[chan model.Ping]struct{} clients map[chan model.Ping]struct{}
register chan chan model.Ping register chan chan model.Ping
unregister chan chan model.Ping unregister chan chan model.Ping
broadcast chan model.Ping broadcast chan model.Ping
shutdownOnce sync.Once
} }
// NewStreamHub constructs a hub. // NewStreamHub constructs a hub.
@@ -56,10 +58,12 @@ func (h *StreamHub) Run(ctx context.Context) {
// shutdown closes all client channels when the hub stops. // shutdown closes all client channels when the hub stops.
func (h *StreamHub) shutdown() { func (h *StreamHub) shutdown() {
for client := range h.clients { h.shutdownOnce.Do(func() {
close(client) for client := range h.clients {
} close(client)
h.clients = make(map[chan model.Ping]struct{}) }
h.clients = make(map[chan model.Ping]struct{})
})
} }
// Broadcast sends message to all subscribers. // Broadcast sends message to all subscribers.