Skip to content

Commit c5bee92

Browse files
GRACENOBLEclaude
andcommitted
fix(websocket): address CodeRabbit review findings
- hub: make Publish non-blocking (select/default) to prevent worker stall - client: use non-blocking Unregister send to prevent goroutine leak on shutdown - client: replace //nolint:errcheck with explicit error checks throughout ReadPump/WritePump - ws_handler: restrict CheckOrigin to BLUEPRINT_WS_ALLOWED_ORIGIN in non-debug mode - WebSocketManager: close existing socket before opening on repeated connect() calls - useWebSocket: handle pre-existing query params when appending ?token= (use & separator) - tests: add regression test for URL with existing query params - docs: add language identifier to unlabeled fenced code blocks (markdownlint MD040) - .env.example: document BLUEPRINT_WS_ALLOWED_ORIGIN Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent d75630d commit c5bee92

9 files changed

Lines changed: 64 additions & 17 deletions

File tree

‎backend/.env.example‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,7 @@ FIREBASE_PROJECT_ID=
1515
# Service account key as a single-line JSON string. Get from: Firebase Console → Project Settings → Service Accounts → Generate new private key
1616
FIREBASE_SERVICE_ACCOUNT_JSON=
1717
# Sentry error tracking DSN (optional; leave empty to disable)
18-
SENTRY_DSN=
18+
SENTRY_DSN=
19+
# WebSocket allowed origin in staging/production — e.g. https://example.com
20+
# Leave empty to deny all cross-origin WebSocket connections in non-debug mode.
21+
BLUEPRINT_WS_ALLOWED_ORIGIN=http://localhost:3000

‎backend/docs/websocket.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ Each WebSocket connection spawns two goroutines: `ReadPump` and `WritePump` (on
6262
The Hub serialises all mutations (register / unregister / broadcast) through a `select` loop
6363
so no locking is needed on its internal `clients` map.
6464

65-
```
65+
```text
6666
caller goroutine
6767
│ hub.Publish(...)
6868
▼
@@ -95,7 +95,7 @@ Ping/pong keepalive: `pingPeriod = 54s`, `pongWait = 60s`, `writeWait = 10s`.
9595

9696
## Route — GET /ws
9797

98-
```
98+
```text
9999
GET /ws?token=<firebase-id-token>
100100
```
101101

‎backend/internal/infrastructure/ws/client.go‎

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -38,11 +38,18 @@ func NewClient(hub *Hub, conn *websocket.Conn) *Client {
3838
// It unregisters the client and closes the connection when done.
3939
func (c *Client) ReadPump() {
4040
defer func() {
41-
c.hub.Unregister <- c
41+
// Non-blocking: if Hub.Run has already exited (ctx cancelled) there is no
42+
// receiver on Unregister. The Hub already closed c.Send in that case.
43+
select {
44+
case c.hub.Unregister <- c:
45+
default:
46+
}
4247
c.conn.Close()
4348
}()
4449
c.conn.SetReadLimit(maxMessageSize)
45-
c.conn.SetReadDeadline(time.Now().Add(pongWait)) //nolint:errcheck
50+
if err := c.conn.SetReadDeadline(time.Now().Add(pongWait)); err != nil {
51+
return
52+
}
4653
c.conn.SetPongHandler(func(string) error {
4754
return c.conn.SetReadDeadline(time.Now().Add(pongWait))
4855
})
@@ -68,26 +75,36 @@ func (c *Client) WritePump() {
6875
for {
6976
select {
7077
case msg, ok := <-c.Send:
71-
c.conn.SetWriteDeadline(time.Now().Add(writeWait)) //nolint:errcheck
78+
if err := c.conn.SetWriteDeadline(time.Now().Add(writeWait)); err != nil {
79+
return
80+
}
7281
if !ok {
73-
c.conn.WriteMessage(websocket.CloseMessage, []byte{}) //nolint:errcheck
82+
_ = c.conn.WriteMessage(websocket.CloseMessage, []byte{})
7483
return
7584
}
7685
w, err := c.conn.NextWriter(websocket.TextMessage)
7786
if err != nil {
7887
return
7988
}
80-
w.Write(msg) //nolint:errcheck
89+
if _, err := w.Write(msg); err != nil {
90+
return
91+
}
8192
// Drain any queued messages into the same WebSocket frame.
8293
for i := len(c.Send); i > 0; i-- {
83-
w.Write([]byte{'\n'}) //nolint:errcheck
84-
w.Write(<-c.Send) //nolint:errcheck
94+
if _, err := w.Write([]byte{'\n'}); err != nil {
95+
break
96+
}
97+
if _, err := w.Write(<-c.Send); err != nil {
98+
break
99+
}
85100
}
86101
if err := w.Close(); err != nil {
87102
return
88103
}
89104
case <-ticker.C:
90-
c.conn.SetWriteDeadline(time.Now().Add(writeWait)) //nolint:errcheck
105+
if err := c.conn.SetWriteDeadline(time.Now().Add(writeWait)); err != nil {
106+
return
107+
}
91108
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
92109
return
93110
}

‎backend/internal/infrastructure/ws/hub.go‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package ws
33
import (
44
"context"
55
"encoding/json"
6+
"errors"
67
)
78

89
// Hub maintains the set of active WebSocket clients and broadcasts messages to them.
@@ -67,6 +68,10 @@ func (h *Hub) Publish(msgType string, payload any) error {
6768
if err != nil {
6869
return err
6970
}
70-
h.broadcast <- env
71-
return nil
71+
select {
72+
case h.broadcast <- env:
73+
return nil
74+
default:
75+
return errors.New("ws: broadcast channel full, message dropped")
76+
}
7277
}

‎backend/internal/transport/handlers/ws_handler.go‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package handlers
22

33
import (
44
"net/http"
5+
"os"
56

67
"github.com/gin-gonic/gin"
78
"github.com/gorilla/websocket"
@@ -12,8 +13,18 @@ import (
1213
var upgrader = websocket.Upgrader{
1314
ReadBufferSize: 1024,
1415
WriteBufferSize: 1024,
15-
// TODO: restrict to known origins in production.
16-
CheckOrigin: func(r *http.Request) bool { return true },
16+
// In debug mode (local dev) all origins are allowed so browsers can connect
17+
// from any port. In staging/production, restrict to BLUEPRINT_WS_ALLOWED_ORIGIN.
18+
CheckOrigin: func(r *http.Request) bool {
19+
if gin.IsDebugging() {
20+
return true
21+
}
22+
allowed := os.Getenv("BLUEPRINT_WS_ALLOWED_ORIGIN")
23+
if allowed == "" {
24+
return false
25+
}
26+
return r.Header.Get("Origin") == allowed
27+
},
1728
}
1829

1930
// WsHandler godoc

‎mobile/app/src/main/java/com/company/template/websocket/WebSocketManager.kt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ class WebSocketManager(
4444
private set
4545

4646
fun connect(token: String?) {
47+
socket?.close(1000, "reconnecting")
48+
socket = null
4749
active = true
4850
currentToken = token
4951
retryCount = 0

‎web/docs/websocket.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ const { isConnected, lastMessage, send } = useWebSocket({
5959

6060
After a disconnect, the hook retries with exponential backoff capped at 30 seconds:
6161

62-
```
62+
```text
6363
delay = min(1000ms × 2^retryCount, 30 000ms)
6464
```
6565

‎web/lib/useWebSocket.test.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,13 @@ describe('useWebSocket', () => {
6666
expect(MockWebSocket.instances[0].url).toBe('ws://localhost:8080/ws?token=abc123')
6767
})
6868

69+
it('appends token with & when url already has query params', () => {
70+
renderHook(() =>
71+
useWebSocket({ url: 'ws://localhost:8080/ws?room=1', token: 'abc123' }),
72+
)
73+
expect(MockWebSocket.instances[0].url).toBe('ws://localhost:8080/ws?room=1&token=abc123')
74+
})
75+
6976
it('sets isConnected true after open', () => {
7077
const { result } = renderHook(() => useWebSocket({ url: 'ws://localhost:8080/ws' }))
7178
act(() => MockWebSocket.instances[0].simulateOpen())

‎web/lib/useWebSocket.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,9 @@ export function useWebSocket({
4949
connectRef.current = () => {
5050
if (unmountedRef.current) return
5151

52-
const wsUrl = token ? `${url}?token=${encodeURIComponent(token)}` : url
52+
const wsUrl = token
53+
? `${url}${url.includes('?') ? '&' : '?'}token=${encodeURIComponent(token)}`
54+
: url
5355
const ws = new WebSocket(wsUrl)
5456
wsRef.current = ws
5557

0 commit comments

Comments
 (0)