|
| 1 | +package handlers |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "log" |
| 7 | + "strconv" |
| 8 | + "strings" |
| 9 | + "sync" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/jackc/pgx/v5" |
| 13 | +) |
| 14 | + |
| 15 | +// Event type discriminators for the WebSocket envelope. Adding a new event |
| 16 | +// type means adding a constant here and a producer that dispatches it. |
| 17 | +const ( |
| 18 | + eventNewMsg = "new_msg" |
| 19 | +) |
| 20 | + |
| 21 | +// wsEnvelope is the JSON shape of every frame pushed over a WebSocket. The |
| 22 | +// Type field lets clients route events; Data carries the event-specific body. |
| 23 | +type wsEnvelope struct { |
| 24 | + Type string `json:"type"` |
| 25 | + Data interface{} `json:"data"` |
| 26 | +} |
| 27 | + |
| 28 | +// Hub maintains the set of connected WebSocket clients and fans out database |
| 29 | +// notifications to the clients they pertain to. A single dedicated PostgreSQL |
| 30 | +// connection LISTENs on new_msg_to for the whole process, so the number of |
| 31 | +// connected clients does not affect the size of the database connection pool. |
| 32 | +type Hub struct { |
| 33 | + // buildItem produces the message payload pushed for a notification. It is |
| 34 | + // a field (rather than a *MessageHandler call) so dispatch can be unit |
| 35 | + // tested without a database. |
| 36 | + buildItem func(ctx context.Context, msgID int64, recipient string) (*messageListItem, error) |
| 37 | + |
| 38 | + mu sync.RWMutex |
| 39 | + // registry maps a lower-cased user address to the set of that user's |
| 40 | + // currently connected clients (a user may have several connections). |
| 41 | + registry map[string]map[*wsClient]struct{} |
| 42 | +} |
| 43 | + |
| 44 | +// NewHub creates a Hub that builds pushed message payloads via msgs. |
| 45 | +func NewHub(msgs *MessageHandler) *Hub { |
| 46 | + return &Hub{ |
| 47 | + buildItem: msgs.messageItemFor, |
| 48 | + registry: make(map[string]map[*wsClient]struct{}), |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +// Register adds a client to the registry under its authenticated address. |
| 53 | +func (h *Hub) Register(c *wsClient) { |
| 54 | + h.mu.Lock() |
| 55 | + defer h.mu.Unlock() |
| 56 | + set := h.registry[c.addr] |
| 57 | + if set == nil { |
| 58 | + set = make(map[*wsClient]struct{}) |
| 59 | + h.registry[c.addr] = set |
| 60 | + } |
| 61 | + set[c] = struct{}{} |
| 62 | +} |
| 63 | + |
| 64 | +// Unregister removes a client from the registry. |
| 65 | +func (h *Hub) Unregister(c *wsClient) { |
| 66 | + h.mu.Lock() |
| 67 | + defer h.mu.Unlock() |
| 68 | + set := h.registry[c.addr] |
| 69 | + if set == nil { |
| 70 | + return |
| 71 | + } |
| 72 | + delete(set, c) |
| 73 | + if len(set) == 0 { |
| 74 | + delete(h.registry, c.addr) |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +// Run owns the dedicated listener connection. It blocks until ctx is cancelled, |
| 79 | +// reconnecting with capped exponential backoff if the connection drops. |
| 80 | +func (h *Hub) Run(ctx context.Context) { |
| 81 | + const maxBackoff = 30 * time.Second |
| 82 | + backoff := time.Second |
| 83 | + for ctx.Err() == nil { |
| 84 | + err := h.listen(ctx, func() { backoff = time.Second }) |
| 85 | + if ctx.Err() != nil { |
| 86 | + return |
| 87 | + } |
| 88 | + log.Printf("ws hub: listener stopped (%v); reconnecting in %s", err, backoff) |
| 89 | + select { |
| 90 | + case <-ctx.Done(): |
| 91 | + return |
| 92 | + case <-time.After(backoff): |
| 93 | + } |
| 94 | + if backoff < maxBackoff { |
| 95 | + backoff *= 2 |
| 96 | + } |
| 97 | + } |
| 98 | +} |
| 99 | + |
| 100 | +// listen opens a dedicated connection, LISTENs on new_msg_to, and dispatches |
| 101 | +// every notification until the connection fails or ctx is cancelled. onConnected |
| 102 | +// is invoked once the LISTEN has succeeded so the caller can reset its backoff. |
| 103 | +func (h *Hub) listen(ctx context.Context, onConnected func()) error { |
| 104 | + // An empty connection string makes pgx read the standard PG* environment |
| 105 | + // variables, exactly as the pgxpool in db.New does. |
| 106 | + conn, err := pgx.Connect(ctx, "") |
| 107 | + if err != nil { |
| 108 | + return err |
| 109 | + } |
| 110 | + defer conn.Close(context.Background()) |
| 111 | + |
| 112 | + if _, err := conn.Exec(ctx, "LISTEN new_msg_to"); err != nil { |
| 113 | + return err |
| 114 | + } |
| 115 | + log.Println("ws hub: listening on new_msg_to") |
| 116 | + onConnected() |
| 117 | + |
| 118 | + for { |
| 119 | + n, err := conn.WaitForNotification(ctx) |
| 120 | + if err != nil { |
| 121 | + return err |
| 122 | + } |
| 123 | + msgID, addr, ok := parseNotifyPayload(n.Payload) |
| 124 | + if !ok { |
| 125 | + log.Printf("ws hub: ignoring malformed notification payload %q", n.Payload) |
| 126 | + continue |
| 127 | + } |
| 128 | + h.dispatch(ctx, msgID, addr) |
| 129 | + } |
| 130 | +} |
| 131 | + |
| 132 | +// parseNotifyPayload parses a new_msg_to payload of the form "msgID,addr". |
| 133 | +func parseNotifyPayload(payload string) (msgID int64, addr string, ok bool) { |
| 134 | + comma := strings.IndexByte(payload, ',') |
| 135 | + if comma < 0 { |
| 136 | + return 0, "", false |
| 137 | + } |
| 138 | + id, err := strconv.ParseInt(payload[:comma], 10, 64) |
| 139 | + if err != nil { |
| 140 | + return 0, "", false |
| 141 | + } |
| 142 | + addr = payload[comma+1:] |
| 143 | + if addr == "" { |
| 144 | + return 0, "", false |
| 145 | + } |
| 146 | + return id, addr, true |
| 147 | +} |
| 148 | + |
| 149 | +// dispatch pushes message msgID to every client connected as addr. The message |
| 150 | +// is fetched and marshalled only when at least one such client is connected, so |
| 151 | +// notifications for addresses with no live WebSocket cost nothing beyond a map |
| 152 | +// lookup. addr originates from a msg_to/msg_add_to row, so any client connected |
| 153 | +// as addr is by definition a participant of the message. |
| 154 | +func (h *Hub) dispatch(ctx context.Context, msgID int64, addr string) { |
| 155 | + h.mu.RLock() |
| 156 | + set := h.registry[strings.ToLower(addr)] |
| 157 | + clients := make([]*wsClient, 0, len(set)) |
| 158 | + for c := range set { |
| 159 | + clients = append(clients, c) |
| 160 | + } |
| 161 | + h.mu.RUnlock() |
| 162 | + if len(clients) == 0 { |
| 163 | + return |
| 164 | + } |
| 165 | + |
| 166 | + item, err := h.buildItem(ctx, msgID, addr) |
| 167 | + if err != nil { |
| 168 | + log.Printf("ws hub: build message %d for %s: %v", msgID, addr, err) |
| 169 | + return |
| 170 | + } |
| 171 | + payload, err := json.Marshal(wsEnvelope{Type: eventNewMsg, Data: item}) |
| 172 | + if err != nil { |
| 173 | + log.Printf("ws hub: marshal message %d: %v", msgID, err) |
| 174 | + return |
| 175 | + } |
| 176 | + |
| 177 | + for _, c := range clients { |
| 178 | + select { |
| 179 | + case c.send <- payload: |
| 180 | + default: |
| 181 | + // Slow client: drop the connection rather than stall the |
| 182 | + // shared fan-out for every other client. |
| 183 | + log.Printf("ws hub: client %s send buffer full, closing", c.addr) |
| 184 | + c.close() |
| 185 | + } |
| 186 | + } |
| 187 | +} |
0 commit comments