| 47 | } |
| 48 | |
| 49 | func (h *Hub) run() { |
| 50 | defer close(h.closed) |
| 51 | defer h.Stop() |
| 52 | |
| 53 | for { |
| 54 | select { |
| 55 | case <-h.quit: |
| 56 | return |
| 57 | case <-h.ctx.Done(): |
| 58 | return |
| 59 | case message := <-h.broadcast: |
| 60 | staleClients := []string{} |
| 61 | for id, client := range h.clients { |
| 62 | if client == nil { |
| 63 | staleClients = append(staleClients, id) |
| 64 | continue |
| 65 | } |
| 66 | |
| 67 | if _, err := client.Write(message); err != nil { |
| 68 | slog.WarnContext(h.ctx, "failed to write websocket message", |
| 69 | "client_id", id, |
| 70 | "error", err) |
| 71 | staleClients = append(staleClients, id) |
| 72 | } |
| 73 | } |
| 74 | if len(staleClients) > 0 { |
| 75 | slog.WarnContext(h.ctx, "evicting stale websocket clients", |
| 76 | "count", len(staleClients), |
| 77 | "client_ids", staleClients) |
| 78 | h.mux.Lock() |
| 79 | for _, id := range staleClients { |
| 80 | if client, ok := h.clients[id]; ok { |
| 81 | if client != nil { |
| 82 | client.Stop() |
| 83 | } |
| 84 | delete(h.clients, id) |
| 85 | } |
| 86 | } |
| 87 | h.mux.Unlock() |
| 88 | } |
| 89 | } |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | func (h *Hub) Register(client *Client) error { |
| 94 | if client == nil { |